//
// cocos2d Hello World example
// http://www.cocos2d-iphone.org
//

// Import the interfaces
#import "GameScene.h"
#import "MathTools.h"
#import "CGameSoundPlayW.h"
#import "CMutSoundPlayW.h"
#import "FileTools.h"

@implementation EnemyEnter

@synthesize interval = _interval;
@synthesize type = _type;

+(id)EnemyEnterMake:(int) interval type:(int)type
{
	EnemyEnter* enter = [[[EnemyEnter alloc] init] autorelease];
	enter.interval = interval;
	enter.type = type;
	return enter;
}

-(id) init
{
	if ((self = [super init])) 
	{
		_interval = 0;
		_type = 0;
	}
	return self;
}

-(void) dealloc
{
	[super dealloc];
}


@end

// HelloWorld implementation
@implementation Game


@synthesize selectTower = m_SelectTower;

static Game* GameLayer = nil;
static CCScene * GameCCScene = nil;

+(id) scene
{
	// 'scene' is an autorelease object.
	if(GameCCScene == nil)
		GameCCScene = [CCScene node];
	
	if(GameLayer != nil)
		return GameCCScene;
	
	GameLayer = [Game node];
	// add layer as a child to scene
	[GameCCScene addChild: GameLayer z:1];
	
	CLoadingW * pLoad = [CLoadingW ShareLoading];
	
	[GameCCScene addChild:pLoad z:5];
	
	pLoad.loadingOver = NO;
	
	// return the scene
	return GameCCScene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init] )) {
		//enable touch event
		loadImageNum = 0;
		[self schedule:@selector(LoadImage) interval:1.0f];
	}

	return self;
}

-(void)InitSprite
{
	self.isTouchEnabled = YES;
	
	[self InitGameData];
	//加载地图
	[self InitMap];
	//初始化图片
	[self InitUI];
	//武将
	[self InitWarrior];
	
	CGSize size = [[CCDirector sharedDirector] winSize];
	CLoadingW * pLoad = [CLoadingW ShareLoading];
	if(pLoad.loadingOver)//加载完移除loading动画
	 {
		[GameCCScene removeChild:pLoad cleanup:NO];
		[self schedule:@selector(step:)];
	 }
	 else//检测loading动画是否跑完
	 {
		 [self schedule:@selector(CheckLoadOver) interval:1.0f];
	 }
}

-(void)CheckLoadOver
{
	CLoadingW * pLoad = [CLoadingW ShareLoading];
	if(pLoad.loadingOver)
	{
		[GameCCScene removeChild:pLoad cleanup:	NO];
		[self unschedule:@selector(CheckLoadOver)];
		[self schedule:@selector(step:)];
	}
	else
	{
		[self schedule:@selector(CheckLoadOver) interval:1.0f];
	}
}

//初始化地图
-(void) InitMap
{
	//初始化地图
	m_MapManager = [[MapManager alloc] init];
	switch ([[Parameter sharedParameter] stage]) 
	{
		case 1:
		{
			[m_MapManager LoadMap:"hulao.map" type:0];
			Location* location = [m_MapManager GetEnd];
			[m_MapManager MarkFullMap:location];
			[m_MapManager CopyBack];
			m_Map = [CCSprite spriteWithFile:@"HuLao.png"];
			[m_Map setScale:1/1.5];
			
			
			[self LoadWaveFile:"hulao.csv"];
			EnemyEnter *enter = [[m_EnemyWave objectAtIndex:0] objectAtIndex:0];
			m_WaveInterval = enter.interval;
		}
			break;
		case 2:
		{
			[m_MapManager LoadMap:"changbanpo.map" type:0];
			Location* location = [m_MapManager GetEnd];
			[m_MapManager MarkFullMap:location];
			[m_MapManager CopyBack];
			m_Map = [CCSprite spriteWithFile:@"ChangBan.png"];
			[m_Map setScale:1/1.5];
			[self LoadWaveFile:"changbanpo.csv"];
			EnemyEnter *enter = [[m_EnemyWave objectAtIndex:0] objectAtIndex:0];
			m_WaveInterval = enter.interval;
			
		}
			break;
		case 3:
		{
			[m_MapManager LoadMap:"dingjunshan.map" type:0];
			Location* location = [m_MapManager GetEnd];
			[m_MapManager MarkFullMap:location];
			[m_MapManager CopyBack];
			m_Map = [CCSprite spriteWithFile:@"DingShan.png"];
			[m_Map setScale:1/1.5];
			[self LoadWaveFile:"dingjun.csv"];
			EnemyEnter *enter = [[m_EnemyWave objectAtIndex:0] objectAtIndex:0];
			m_WaveInterval = enter.interval;
		}
			break;
		case 4:
		{
			[m_MapManager LoadMap:"nanzhong.map" type:1];
			Location* location = [m_MapManager GetEnd];
			[m_MapManager MarkFullMap:location];
			[m_MapManager CopyBack];
			m_Map = [CCSprite spriteWithFile:@"Nanzhong.png"];
			[m_Map setScale:10.f/18.f];
			[self LoadWaveFile:"nanzhong.csv"];
			EnemyEnter *enter = [[m_EnemyWave objectAtIndex:0] objectAtIndex:0];
			m_WaveInterval = enter.interval;
		}
			break;
		default:
			break;
	}
	
	[m_MapManager MarkWarriorMap:[m_MapManager GetStart]];
	[m_MapManager WarriorCopyBack];
	
	m_Map.position = ccp(240,160);
	[self addChild:m_Map];
}

//初始化数据,包括敌兵,箭塔,波次等
-(void) InitGameData
{
	//动画数据

	[self InitCAnimationStore];
	
	
	//触控状态
	m_TouchState = TOUCH_DEFAULT;
	
	//触点数量
	m_TouchPointCount = 0;
	
	//剩余生命
	m_LifeLeft = 0;
	
	//要放置的箭塔类型
	m_TowerType = 0;
	//初始化数组
	//子弹数组
	m_Bullet = [[NSMutableArray alloc] init];
	//塔的数组
	m_TowerList = [[NSMutableArray alloc] init];
	//战鼓台数组
	m_PowerUpTower = [[NSMutableArray alloc] init];
	//小兵数组
	m_EnemyList = [[NSMutableArray alloc] init];
	//波次数据
	m_EnemyWave = [[NSMutableArray alloc] init];
	m_WaveNum = 0;
	m_IndexInWave = 0;
	m_WaveInterval = 0;
	//经验
	m_WarriorExp = 0;
	//战功
	m_Exploit = 0;
	//选中的技能
	m_SkillSelect = 0;
	
	//八卦阵数组
	m_BaGuaEffect = [[NSMutableArray alloc] init];
	m_LuoLeiEffect = [[NSMutableArray alloc] init];
	m_TouQuEffect = [[NSMutableArray alloc] init];
	
	//箭塔的区域数据对应在图片资源上的区域
	m_TowerRectInResource[0] = CGRectMake(168, 168, 84, 84);
	m_TowerRectInResource[1] = CGRectMake(84, 168, 84, 84);
	m_TowerRectInResource[2] = CGRectMake(0, 168, 84, 84);
	m_TowerRectInResource[3] = CGRectMake(168, 84, 84, 84);
	m_TowerRectInResource[4] = CGRectMake(84, 84, 84, 84);
	m_TowerRectInResource[5] = CGRectMake(0, 84, 84, 84);
	m_TowerRectInResource[6] = CGRectMake(168, 0, 84, 84);
	m_TowerRectInResource[7] = CGRectMake(84, 0, 84, 84);
	m_TowerRectInResource[8] = CGRectMake(0, 0, 84, 84);
	
	AccelerateNum = 1;
}


//初始化UI,包括触控图标等
-(void) InitUI
{
	m_IconArrow = [[self AddWeaponIcon:0] retain];
	m_IconPoison = [[self AddWeaponIcon:1] retain];
	m_IconPuncture = [[self AddWeaponIcon:2] retain];
	m_IconMangonel = [[self AddWeaponIcon:3] retain];
	m_IconPowerUpTower = [[self AddWeaponIcon:4] retain];
	
	//金钱
	m_Money = 100;
	NSString *smoney = [[NSString alloc] initWithFormat:@"money %d", m_Money];
	//m_MoneyLabel = [[CCLabel labelWithString:smoney fontName:@"Marker Felt" fontSize:16] retain];
	m_MoneyLabel = [[CCBitmapFontAtlas bitmapFontAtlasWithString:smoney fntFile:@"arial16.fnt"] retain];
	m_MoneyLabel.position = ccp(50, 310);
	m_MoneyLabel.color = ccc3(0, 0, 0);
	[self addChild:m_MoneyLabel z:2];
	[smoney release];
	
	
	//波次
	NSString *wavestr = [NSString stringWithFormat:@"wave %d", m_WaveNum + 1];
	m_WaveLabel = [[CCBitmapFontAtlas bitmapFontAtlasWithString:wavestr fntFile:@"arial16.fnt"] retain];
	m_WaveLabel.position = ccp(240, 310);
	m_WaveLabel.color = ccc3(255, 0, 0);
	[self addChild:m_WaveLabel];
	
	
	//触摸区域
	CGPoint touchPoint = [self WeaponTouchPoint:NormalWeapon];
	m_RectIconArrow = CGRectMake(touchPoint.x-32, touchPoint.y-32, 64, 64);
	touchPoint = [self WeaponTouchPoint:Poison];
	m_RectIconPoison = CGRectMake(touchPoint.x-32, touchPoint.y-32, 64, 64);
	touchPoint = [self WeaponTouchPoint:Puncture];
	m_RectIconPuncture = CGRectMake(touchPoint.x-32, touchPoint.y-32, 64, 64);
	touchPoint = [self WeaponTouchPoint:Mangonel];
	m_RectIconMangonel = CGRectMake(touchPoint.x-32, touchPoint.y-32, 64, 64);
	touchPoint = [self WeaponTouchPoint:PowerUpTower];
	m_RectIconPowerUpTower = CGRectMake(touchPoint.x-32, touchPoint.y-32, 64, 64);
	
	
	//拆塔,升级的精灵
	m_SpriteSelect = [[CCSprite spriteWithFile:@"fanwei.png"] retain];
	m_SpriteSelect.position = ccp(1000, 1000);
	CCLabel *chai = [CCLabel labelWithString:@"拆" fontName:@"Marker Felt" fontSize:20];
	chai.position = ccp(30, 75);
	CCLabel *chaiMoney = [CCLabel labelWithString:@"0" fontName:@"Marker Felt" fontSize:20];
	chaiMoney.position = ccp(30, 55);
	CCLabel *sheng = [CCLabel labelWithString:@"升" fontName:@"Marker Felt" fontSize:20];
	sheng.position = ccp(120, 75);
	CCLabel* shengMoney = [CCLabel labelWithString:@"0" fontName:@"Marker Felt" fontSize:20];
	shengMoney.position = ccp(120, 55);
	[m_SpriteSelect addChild:chai];
	[m_SpriteSelect addChild:sheng];
	[m_SpriteSelect addChild:chaiMoney z:1 tag:kChaiMoney];
	[m_SpriteSelect addChild:shengMoney z:1 tag:kUpMoney];
	[m_Map addChild:m_SpriteSelect z:20];
	m_SelectTower = nil;	
	
	int width = 164/4;
	int height = 41;
	int icon_x = 455;
	int icon_y = 320-63;
	int y_offset = height+6;
	//武将技能Icon
	CGRect iconRect= CGRectMake(0, 0, width, height);
	m_IconSkill_1 = [CCSprite spriteWithFile:@"iGUI_hero01_fx_btn.png" rect:iconRect];
	m_IconSkill_1.position = ccp(icon_x, icon_y);
	[self addChild:m_IconSkill_1 z:1];
	
	iconRect= CGRectMake(width, 0, width, height);
	icon_y = icon_y-y_offset;
	m_IconSkill_2 = [CCSprite spriteWithFile:@"iGUI_hero01_fx_btn.png"rect:iconRect];
	m_IconSkill_2.position = ccp(icon_x, icon_y);
	[self addChild:m_IconSkill_2 z:1];
	
	iconRect= CGRectMake(width*2, 0, width, height);
	m_IconSkill_3 = [CCSprite spriteWithFile:@"iGUI_hero01_fx_btn.png"rect:iconRect];
	icon_y = icon_y-y_offset;
	m_IconSkill_3.position = ccp(icon_x, icon_y);
	[self addChild:m_IconSkill_3 z:1];
	
	iconRect= CGRectMake(width*3, 0, width, height);
	icon_y = icon_y-y_offset;
	m_IconSkill_4 = [CCSprite spriteWithFile:@"iGUI_hero01_fx_btn.png"rect:iconRect];
	m_IconSkill_4.position = ccp(icon_x, icon_y);
	[self addChild:m_IconSkill_4 z:1];
	
	m_TouchRectSkill_1 = CGRectMake(m_IconSkill_1.position.x-20, m_IconSkill_1.position.y-20, 41, 41);
	m_TouchRectSkill_2 = CGRectMake(m_IconSkill_2.position.x-20, m_IconSkill_2.position.y-20, 41, 41);
	m_TouchRectSkill_3 = CGRectMake(m_IconSkill_3.position.x-20, m_IconSkill_3.position.y-20, 41, 41);
	m_TouchRectSkill_4 = CGRectMake(m_IconSkill_4.position.x-20, m_IconSkill_4.position.y-20, 41, 41);

	__BaGuaOneAction = [[NSMutableArray alloc] init];
	__BaGuaTwoAction = [[NSMutableArray alloc] init];
	__LuoLeiOneAction = [[NSMutableArray alloc] init];
	__LuoLeiTwoAction = [[NSMutableArray alloc] init];
	__TouquOneAction = [[NSMutableArray alloc] init];
	__TouquTwoAction = [[NSMutableArray alloc] init];
}

//初始化武将
-(void) InitWarrior
{
	//武将数据
	m_Warrior = [[Guanyu warrior] retain];
	[m_Warrior setScale:0.8];
	CGPoint warriorPos = [self GetPos:[m_MapManager GetEnd]];
	m_Warrior.location = [m_MapManager GetEnd];
	m_Warrior.end = [m_MapManager GetEnd];
	m_Warrior.nextLocation = [m_MapManager GetWarriorNextLocation:[m_MapManager GetEnd]];
	m_Warrior.direction = [self GetDirectionFromLocation:m_Warrior.location toLocation:m_Warrior.nextLocation];
	m_Warrior.position = warriorPos;
	
	//m_Warrior.position.y = m_Warrior.position.y+10;
	
	NSString *levelStr = [NSString stringWithFormat:@"%d", (int)m_Warrior.level];
	CCLabel *levelLabel = [CCBitmapFontAtlas bitmapFontAtlasWithString:levelStr fntFile:@"arial16.fnt"];
	levelLabel.position = ccp(24, 10);
	
	NSString *stateStr = [NSString stringWithFormat:@"%d", m_Warrior.state];
	CCLabel *stateLabel = [CCBitmapFontAtlas bitmapFontAtlasWithString:stateStr fntFile:@"arial16.fnt"];
	stateLabel.position = ccp(24, 30);
	
	[m_Warrior addChild:levelLabel z:0 tag:kWarriorLevel];
	[m_Warrior addChild:stateLabel z:0 tag:kWarriorState];
	
	[m_Map addChild:m_Warrior z:LAYER_ITEM_WARRIOR];
	
	[self InitGuanyuAnimation];
	
	[self ChangeWarrirDirection:1 oldKind:GUAN_WAIT_LEFT actionKind:GUAN_WAIT_LEFT];
	
	[self AddApertureGuanYu]; 
	
	__touchSkillArray = [[NSMutableArray alloc] init];
	__touchLocArray = [[NSMutableArray alloc]init];
	//[m_Warrior setTextureRect:CGRectMake(0, 0, 10, 10)];
}


-(void) step:(ccTime)dt
{
	NSString *smoney = [[NSString alloc] initWithFormat:@"money %d", m_Money];
	[m_MoneyLabel setString:smoney];
	[smoney release];
	NSString *wavestr = [NSString stringWithFormat:@"wave %d", m_WaveNum +1];
	[m_WaveLabel setString:wavestr];
	[self WaveUpdate];
	[self MoveEnemy];
	//[self TowerFire];
	[self TowerUpdate];
	[self BulletUpdate];
	[self WarriorUpdate];
	[self EffectUpdate];
}

-(void) sampleadd:(ccTime)dt
{
	[self addEnemy:1];
}



-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGPoint locations[10];
	int locations_num = 0;
	for (UITouch *touch in touches) {
		locations[locations_num] = [touch locationInView:[touch view]];
		locations[locations_num] = [[CCDirector sharedDirector] convertToGL:locations[locations_num]];
		locations_num++;
	}
	
	m_TouchPointCount += locations_num;
	
	//同时在屏幕上的触点多于 1 个, 那么进入地图缩放状态
	if (m_TouchPointCount > 1) 
	{
		return;
	}
	
	switch (m_TouchState) 
	{
		case TOUCH_DEFAULT:
		{
			[self TouchesBeganDefault:locations count:locations_num];
		}
			break;
		case TOUCH_ENEMY_SELECT:
		{
			[self TouchesBeganEnemySelect:locations count:locations_num];
		}
			break;
		case TOUCH_TOWER_SELECT:
		{
			[self TouchesBeganTowerSelect:locations count:locations_num];
		}
			break;
		default:
			break;
	}
}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGPoint locations[10];
	int locations_num = 0;
	for (UITouch *touch in touches) {
		locations[locations_num] = [touch locationInView:[touch view]];
		locations[locations_num] = [[CCDirector sharedDirector] convertToGL:locations[locations_num]];
		locations_num++;
	}
	
	switch (m_TouchState) 
	{
		case TOUCH_PUT_TOWER:
		{
			[self TouchesMovePutTower:locations count:locations_num];
		}
			break;
		case TOUCH_PUT_SKILL:
		{
			[self TouchesMovePutSkill:locations count:locations_num];
		}
			break;
		case TOUCH_MAP_SELECT:
		{
			[self TouchesMoveMapSelect:locations count:locations_num];
		}
			break;
		default:
			break;
	}
}

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGPoint locations[10];
	int locations_num = 0;
	for (UITouch *touch in touches) {
		locations[locations_num] = [touch locationInView:[touch view]];
		locations[locations_num] = [[CCDirector sharedDirector] convertToGL:locations[locations_num]];
		locations_num++;
	}
	
	m_TouchPointCount -= locations_num;
	
	switch (m_TouchState) 
	{
		case TOUCH_PUT_TOWER:
		{
			[self TouchesEndPutTower:locations count:locations_num];
		}
			break;
		case TOUCH_TOWER_SELECT:
		{
			[self TouchesEndTowerSelect:locations count:locations_num];
		}
			break;
		case TOUCH_PUT_SKILL:
		{
			[self TouchesEndPutSkill:locations count:locations_num];
		}
			break;
		case TOUCH_MAP_SELECT:
		{
			[self TouchesEndMapSelect:locations count:locations_num];
		}
			break;
		default:
			break;
	}
}

/*触碰操作处理方法*/


//默认状态下触控事件
-(void) TouchesBeganDefault:(CGPoint *)touches count:(int)counts 
{
	if(CGRectContainsPoint(m_RectIconArrow, touches[0]))
	{
		m_TowerType = NormalWeapon+1;
		[self MoveWeaponIconMap:NormalWeapon IsEnable:YES];
		return;
	}
	else if(CGRectContainsPoint(m_RectIconPoison, touches[0]))
	{
		m_TowerType = Poison+1;
		[self MoveWeaponIconMap:Poison IsEnable:YES];
		return;
	}
	else if(CGRectContainsPoint(m_RectIconPuncture, touches[0]))
	{
		m_TowerType = Puncture+1;
		[self MoveWeaponIconMap:Puncture IsEnable:YES];
		return;
	}
	else if(CGRectContainsPoint(m_RectIconMangonel, touches[0]))
	{
		m_TowerType = Mangonel+1;
		[self MoveWeaponIconMap:Mangonel IsEnable:YES];
		return;
	}
	else if(CGRectContainsPoint(m_RectIconPowerUpTower, touches[0]))
	{
		m_TowerType = PowerUpTower+1;
		[self MoveWeaponIconMap:PowerUpTower IsEnable:YES];
		return;
	}
	else if(CGRectContainsPoint(m_TouchRectSkill_1, touches[0])&&[self IsSkillEnable])		
	{
		
		m_TouchState = TOUCH_PUT_SKILL;
		m_SkillSelect = SKILL_BAGUA;
		[self AddSkillAreaMap:NO];
		return;
	}
	else if(CGRectContainsPoint(m_TouchRectSkill_2, touches[0])&&[self IsSkillEnable])
	{
		m_TouchState = TOUCH_PUT_SKILL;
		m_SkillSelect = SKILL_LUOLEI;
		[self AddSkillAreaMap:NO];
		return;
	}
	else if(CGRectContainsPoint(m_TouchRectSkill_3, touches[0])&&[self IsSkillEnable])
	{
		m_TouchState = TOUCH_PUT_SKILL;
		m_SkillSelect = SKILL_TOUQU;
		[self AddSkillAreaMap:NO];
		return;
	}
	else if(CGRectContainsPoint(m_TouchRectSkill_4, touches[0])&&[self IsSkillEnable])
	{
		CGPoint mapPoint = [self ConvertToMap:touches[0]];
		Location* loc = [self GetLocation:mapPoint];
		CGPoint point = [self GetPos:loc];
		m_SkillSelect = SKILL_HUOQIANG;
		[self TouchSKillIcon:loc];
		
		return;
	}

	CGPoint mapPoint = [self ConvertToMap:touches[0]];
	
	for (Tower *tower in m_TowerList) 
	{
		CGRect touchrect = CGRectMake(tower.position.x - 24 , tower.position.y - 24, 48, 48);
		if(CGRectContainsPoint(touchrect, mapPoint))
		{
			self.selectTower = [tower retain];
			m_SpriteSelect.position = tower.position;
			NSString* chaiStr = [NSString stringWithFormat:@"%d", m_SelectTower.sellMoney];
			NSString* shengStr = [NSString stringWithFormat:@"%d", m_SelectTower.levelMoney];
			
			CCLabel* chaiMoney = (CCLabel*)[m_SpriteSelect getChildByTag:kChaiMoney];
			CCLabel* shengMoney = (CCLabel*)[m_SpriteSelect getChildByTag:kUpMoney];
			
			[chaiMoney setString:chaiStr];
			[shengMoney setString:shengStr];
			m_TouchState = TOUCH_TOWER_SELECT;
			return;
		}
	}
	
	for (Tower *tower in m_PowerUpTower) 
	{
		CGRect touchrect = CGRectMake(tower.position.x - 24 , tower.position.y - 24, 48, 48);
		if(CGRectContainsPoint(touchrect, mapPoint))
		{
			
			self.selectTower = tower;
			m_SpriteSelect.position = tower.position;
			NSString* chaiStr = [NSString stringWithFormat:@"%d", m_SelectTower.sellMoney];
			NSString* shengStr = [NSString stringWithFormat:@"%d", m_SelectTower.levelMoney];
			
			CCLabel* chaiMoney = (CCLabel*)[m_SpriteSelect getChildByTag:kChaiMoney];
			CCLabel* shengMoney = (CCLabel*)[m_SpriteSelect getChildByTag:kUpMoney];
			
			[chaiMoney setString:chaiStr];
			[shengMoney setString:shengStr];
			m_TouchState = TOUCH_TOWER_SELECT;
			return;
		}
	}
	
	for (Enemy *enemy in m_EnemyList) 
	{
		CGRect touchrect = CGRectMake(enemy.position.x - 24, enemy.position.y - 24, 48, 48);
		if (CGRectContainsPoint(touchrect, mapPoint)) 
		{
			if (m_EnemySelected)
			{
				[m_EnemySelected release];
			}
			m_EnemySelected = [enemy retain];
			//m_Warrior.state = WARRIOR_ATTACK;
			m_Warrior.target = enemy;
			Location *targetloc = [self GetLocation:m_Warrior.target.position];
			m_Warrior.end = targetloc;
			[targetloc release];
			[m_MapManager MarkWarriorMap:m_Warrior.end];
			[m_MapManager CopyBack];
			[self GuanRunStop:m_Warrior.direction oldAction:m_Warrior.state newAction:WARRIOR_RUN];
			
			return;
		}
	}
	
	Location *touchloc = [self GetLocation:mapPoint];
	if ([m_MapManager EnableMoveToLoc:touchloc fromWarriorLoc:[self GetLocation:m_Warrior.position]]) 
	{
		if(m_Warrior.state == WARRIOR_ATTACK)
		{
			__b_touch = true;
			__b_touchPoint = mapPoint;
		}
		else
		{
			[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_STAND newAction:WARRIOR_RUN];
			[self TouchMovePoint:mapPoint IsEnableMove:YES];
		}

		//m_Warrior.nextLocation = 
	}
	else
	{
		[self TouchMovePoint:mapPoint IsEnableMove:NO];
	}

	[touchloc release];
}

-(void) TouchesMoveDefault:(CGPoint *)touches count:(int)counts
{
	
}

-(void) TouchesEndDefault:(CGPoint *)touches count:(int)counts 
{
	
}


//敌兵选中状态下触控事件
-(void) TouchesBeganEnemySelect:(CGPoint *)touches count:(int)counts 
{
	
}

-(void) TouchesMoveEnemySelect:(CGPoint *)touches count:(int)counts 
{
	
}

-(void) TouchesEndEnemySelect:(CGPoint *)touches count:(int)counts 
{
	
}


//箭塔选中状态下触控事件
-(void) TouchesBeganTowerSelect:(CGPoint *)touches count:(int)counts 
{
	CGPoint mapPoint = [self ConvertToMap:touches[0]];
	CGRect chaiRect = CGRectMake(m_SpriteSelect.position.x - 45 - 20, m_SpriteSelect.position.y - 20, 40, 40);
	CGRect shengRect = CGRectMake(m_SpriteSelect.position.x + 45 - 20, m_SpriteSelect.position.y - 20, 40, 40);
	
	if (CGRectContainsPoint(chaiRect, mapPoint))
	{
		Location* temploc = [self GetLocation:m_SelectTower.position];
		m_Money += m_SelectTower.sellMoney;
		[m_Map removeChild:m_SelectTower cleanup:YES];
		[m_TowerList removeObject:m_SelectTower];
		[m_MapManager RemoveTower:temploc];
		//self.selectTower = nil;
		
		if (1 == [m_MapManager GetType]) 
		{
			[m_MapManager WarriorReset];
			[m_MapManager MarkWarriorMap:m_Warrior.end];
			
			[m_MapManager WarriorCopyBack];
		}
		
		
		
	}
	else if(CGRectContainsPoint(shengRect, mapPoint))
	{
		int money = m_SelectTower.levelMoney;
		if (m_SelectTower.level < 3 && m_Money >= money) 
		{
			[m_SelectTower levelUp];
			m_Money -= money;
		}
	}
	m_SpriteSelect.position = ccp(1000, 1000);
	m_TouchState = TOUCH_DEFAULT;
	return;
}

-(void) TouchesMoveTowerSelect:(CGPoint *)touches count:(int)counts 
{
	
}


-(void) TouchesEndTowerSelect:(CGPoint *)touches count:(int)counts 
{
	
	
}


//地图选中下的触控事件
-(void) TouchesMoveMapSelect:(CGPoint *)touches count:(int)counts 
{
	
}


-(void) TouchesEndMapSelect:(CGPoint *)touches count:(int)counts 
{
	
}


-(void) TouchesBeganPutTower:(CGPoint *)touches count:(int)counts
{
	
}

//放塔操作的触控事件
-(void) TouchesMovePutTower:(CGPoint *)touches count:(int)counts 
{
	if(__bMoveWeaponIcon==false)
	{
		[self WeaponIconMove:NO];
		__bMoveWeaponIcon = true;
	}
	CGPoint mapPoint = [self ConvertToMap:touches[0]];
	Location* loc = [self GetLocation:mapPoint];
	CGPoint point = [self GetPos:loc];
	m_PutTowerIcon.position = point;
	static BOOL __bIsEnableWeapon = NO;//当前点是否可加武器

	if([m_MapManager EnableTower:loc])
	{
		if(!__bIsEnableWeapon)
		{
			[m_Map removeChild:m_PutTowerIcon cleanup:YES];
			[m_PutTowerIcon release];
			[self MoveWeaponIconMap:m_TowerType-1 IsEnable:YES];
			__bIsEnableWeapon = YES;
		}
		
	}
	else
	{
		if(__bIsEnableWeapon)
		{
			[m_Map removeChild:m_PutTowerIcon cleanup:YES];
			[m_PutTowerIcon release];
			[self MoveWeaponIconMap:m_TowerType-1 IsEnable:NO];
			__bIsEnableWeapon = NO;
		}
	}

	[loc release];
	
}

-(void) TouchesEndPutTower:(CGPoint *)touches count:(int)counts 
{
	__bMoveWeaponIcon = false;
	[self WeaponIconMove:YES];
	float money = [self WeaponPrice:m_TowerType-1];
	
	if ( m_Money >= money) 
	{
		if(0 == [m_MapManager GetType])
		{
			CGPoint mapPoint = [self ConvertToMap:touches[0]];
			
			Location* loc = [self GetLocation:mapPoint];
			if ([m_MapManager EnableTower:loc]) 
			{
				[self addTower:m_TowerType location:loc];
				[m_MapManager PutTower:loc];
				 m_Money -= money;
			}
			[loc release];
		}
		
		else if(1 == [m_MapManager GetType])
		{
			CGPoint mapPoint = [self ConvertToMap:touches[0]];
			Location* loc = [self GetLocation:mapPoint];
			
			if ([m_MapManager EnableTower:loc]) 
			{
				[m_MapManager PutBackTower:loc];
				[m_MapManager MarkFullMap:[m_MapManager GetEnd]];
				[m_MapManager MarkWarriorMap:m_Warrior.end];
				
				if ([m_MapManager EnableTower:[m_MapManager GetStart]]) 
				{
					BOOL bEnable = YES;
					for (Enemy *enemy in m_EnemyList) 
					{
						if (!([m_MapManager EnableTower:enemy.nextLocation])) 
						{
							bEnable = NO;
							break;
						}
						
					}
					if (WARRIOR_STAND == m_Warrior.state) 
					{
						Location *wloc = [self GetLocation:m_Warrior.position];
						if (wloc.x ==  loc.x && wloc.y == loc.y) 
						{
							bEnable = NO;
						}
					}
					else
					{
						if (m_Warrior.nextLocation.x == loc.x && m_Warrior && m_Warrior.nextLocation.y == loc.y) 
						{
							bEnable = NO;
						}
					}
					
					
					
					if (bEnable) 
					{
						[self addTower:m_TowerType location:loc];
						//[m_MapManager PutTower:loc];
						[m_MapManager CopyBack];
						[m_MapManager WarriorCopyBack];
						m_Money -= money;
					}
					else 
					{
						[m_MapManager ResetBack];
					}
					
				}
				else 
				{
					[m_MapManager ResetBack];
				}
			}
			[loc release];
		}
	}
	
	m_TouchState = TOUCH_DEFAULT;
	m_TowerType = 0;
	[m_Map removeChild:m_PutTowerIcon cleanup:YES];
	[m_PutTowerIcon release];
	return;
}

//释放技能的触控事件
-(void) TouchesMovePutSkill:(CGPoint *)touches count:(int)counts 
{
	if(m_SkillSelect == SKILL_HUOQIANG)//暴怒
	{
		return;
	}
	
	if(__bFireSkillIcon==false)//技能ICON开始隐藏
	{
		[self SkillIconMove:NO];
		__bFireSkillIcon = true;
	}
	
	CGPoint mapPoint = [self ConvertToMap:touches[0]];
	Location* loc = [self GetLocation:mapPoint];
	CGPoint point = [self GetPos:loc];

	static BOOL __bIsEnableSkill = NO;//当前点是否可施法
	
	if([m_MapManager IsEnableSkill:loc])
	{
		if(!__bIsEnableSkill)
		{
			[m_Map removeChild:__fireSkill cleanup:YES];
			[self AddSkillAreaMap:YES];
			__bIsEnableSkill = YES;
		}
		
	}
	else
	{
		if(__bIsEnableSkill)
		{
			[m_Map removeChild:__fireSkill cleanup:YES];
			[self AddSkillAreaMap:NO];
			__bIsEnableSkill = NO;
		}
	}
	__fireSkill.position = point;
	[loc release];
}

-(void) TouchesEndPutSkill:(CGPoint *)touches count:(int)counts 
{
	CGPoint mapPoint = [self ConvertToMap:touches[0]];
	Location* loc = [self GetLocation:mapPoint];
	CGPoint point = [self GetPos:loc];
	if(m_SkillSelect != SKILL_HUOQIANG)
	{
		[self SkillIconMove:YES];
		__bFireSkillIcon = false;
		
		if([m_MapManager IsEnableSkill:loc])//使用区域有效
		{
			[self TouchSKillIcon:loc];
			
		}
		[m_Map removeChild:__fireSkill cleanup:YES];
		m_TouchState = TOUCH_DEFAULT;
		
	}
	
	
}









-(void)addEnemy:(int)type
{
	Enemy* enemy = nil;
	Location* location = nil;
	Location* nextLocation = nil;
	location = [[m_MapManager GetStart] retain];
	nextLocation = [m_MapManager GetNextLocation:location];
	int direction = [self GetDirectionFromLocation:location toLocation:nextLocation];
	CGPoint point = [self GetPos:location];
	actionTag++;
	NSString* Id = [NSString stringWithFormat:@"%d",actionTag];
	switch (type)
	{
		case 1:
		{
			enemy = [FootMan enemy];
		}
			break;
			
		case 2:
		{
			enemy = [TengjiaMan enemy];
		}
			break;
		case 3:
		{
			enemy = [Cavalry enemy];

		}
			break;
		case 4:
		{
			enemy = [ManAtArms enemy];
		}
			break;
		case 5:
		{
			enemy = [ElephantMan enemy];
		}
			break;
		case 6:
		{
			enemy = [Tank enemy];
		}
			break;
		case 7:
		{
			enemy = [IronTank enemy];
		}
			break;
		case 8:
		{
			enemy = [MongHuo enemy];

		}
			break;
		default:
			break;
	}
	enemy.hp = (10 + m_WaveNum + 1)*(sqrtf(m_WaveNum +1)/10)*enemy.hp;
	enemy.position = point;
	enemy.location = location;
	enemy.nextLocation = nextLocation;
	enemy.direction = direction;
	enemy.typeName = type-1;
	enemy.idStr = Id;
	[self EnemyMoveActionChange:enemy EnemyKind:(type-1) state:0];
	
	
	[m_Map addChild:enemy z:(LAYER_ITEM_ENEMY + 3*location.y)];
	[m_EnemyList addObject:enemy];
	
	NSString * hpStr = [NSString stringWithFormat:@"%d", (int)enemy.hp];
	CCLabel *hpLabel = [CCBitmapFontAtlas bitmapFontAtlasWithString:hpStr fntFile:@"arial16.fnt"];
	hpLabel.position = ccp(24, 24);
	[enemy addChild:hpLabel z:1 tag:kHpLabel];
	//[enemy setTextureRect:CGRectMake(20, 20, 28, 28)];
	
	[location release];
	[nextLocation release];
}

-(void)addTower:(int)type location:(Location *)loc
{
	CGPoint point = [self GetPos:loc];
	Tower* tower = [Tower tower:type level:1];
	tower.position = point;
	//[tower setScale:0.9];
	
	
	NSString* levelStr = [NSString stringWithFormat:@"%d", tower.level];
	
	CCLabel *levelLabel = [CCLabel labelWithString:levelStr fontName:@"Marker Felt" fontSize:16];
	levelLabel.position = ccp(24, 24);
	//tower.offsetPosition = ccp(0, 50);
	[tower addChild:levelLabel z:1 tag:kLevelLabel];
	
	[m_Map addChild:tower z:(LAYER_ITEM_TOWER + 3*loc.y)];
	
	if (5 == type) 
	{
		[m_PowerUpTower addObject:tower];
	}
	else 
	{
		[m_TowerList addObject:tower];
	}
}




-(void)MoveEnemy
{
	NSMutableArray* array = [[NSMutableArray alloc] init];
	for(Enemy* enemy in m_EnemyList)
	{
		
		//血量大于0且没有到达终点,移动
		if(enemy.hp > 0 && enemy.status !=1)
		{
			CCLabel* hpLabel = (CCLabel*)[enemy getChildByTag:kHpLabel];
			NSString* hpStr = [NSString stringWithFormat:@"%d", (int)enemy.hp];
			[hpLabel setString:hpStr];
			float speed = 0;
			
			//基准速度
			speed = enemy.speed;
			
			for (EffectBaGua* bagua in m_BaGuaEffect) 
			{
				if([self IsImpactCircle:enemy.position range1:enemy.range center2:bagua.position range2:bagua.range])
				{
					speed = speed * bagua.slowDown;
				}
			}
			

			
			//是否被减速
			if (enemy.slowtime > 0) 
			{
				//得到修正后的速度
				speed = speed *(1.f - enemy.slowdown);
				enemy.slowtime--;
			}
			
			
			if (enemy.slowtime <= 0) 
			{
				enemy.slowdown = 0;
			}
			
			//没有被定住,移动
			if (!enemy.isStop) 
			{
				//当前enemy方向的副本
				int __DirectionTemp = enemy.direction;
				
				switch (enemy.direction) {
					case 1:
					{
						enemy.position = ccp(enemy.position.x + speed, enemy.position.y);
						if (enemy.position.x >= ([self GetPos:enemy.nextLocation].x) ) 
						{
							Location *endloc = [m_MapManager GetEnd];
							if (enemy.nextLocation.x == endloc.x && enemy.nextLocation.y == endloc.y) 
							{
								enemy.status = 1;
							}
							else
							{
								float delta = enemy.position.x - ([self GetPos:enemy.nextLocation].x);
								enemy.position = [self GetPos:enemy.nextLocation];
								enemy.location = enemy.nextLocation;
								enemy.nextLocation = [m_MapManager GetNextLocation:enemy.location];
								enemy.direction = [self GetDirectionFromLocation:enemy.location toLocation:enemy.nextLocation];
								switch (enemy.direction) 
								{
									case 1:
									{
										enemy.position.x += delta;
									}
										break;
									case 2:
									{
										enemy.position.y += delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 3:
									{
										enemy.position.y -= delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 4:
									{
										enemy.position.x -= delta;
									}
										break;
									default:
										break;
								}
							}
						}
					}
						break;
					case 2:
					{
						enemy.position = ccp(enemy.position.x, enemy.position.y + speed);
						if (enemy.position.y >= ([self GetPos:enemy.nextLocation].y) ) 
						{
							Location *endloc = [m_MapManager GetEnd];
							if (enemy.nextLocation.x == endloc.x && enemy.nextLocation.y == endloc.y) 
							{
								enemy.status = 1;
							}
							else
							{
								float delta = enemy.position.y - ([self GetPos:enemy.nextLocation].y);
								enemy.position = [self GetPos:enemy.nextLocation];
								enemy.location = enemy.nextLocation;
								enemy.nextLocation = [m_MapManager GetNextLocation:enemy.location];
								enemy.direction = [self GetDirectionFromLocation:enemy.location toLocation:enemy.nextLocation];
								switch (enemy.direction) 
								{
									case 1:
									{
										enemy.position.x += delta;
									}
										break;
									case 2:
									{
										enemy.position.y += delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 3:
									{
										enemy.position.y -= delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 4:
									{
										enemy.position.x -= delta;
									}
										break;
									default:
										break;
								}
								
							}
							
						}
					}
						break;
					case 3:
					{
						//enemy.position.y -= enemy.speed;
						enemy.position = ccp( enemy.position.x, enemy.position.y - speed );
						if (enemy.position.y <= ([self GetPos:enemy.nextLocation].y) ) 
						{
							Location *endloc = [m_MapManager GetEnd];
							if (enemy.nextLocation.x == endloc.x && enemy.nextLocation.y == endloc.y) 
							{
								enemy.status = 1;
							}
							else
							{
								float delta = ([self GetPos:enemy.nextLocation].y) - enemy.position.y;
								enemy.position = [self GetPos:enemy.nextLocation];
								enemy.location = enemy.nextLocation;
								enemy.nextLocation = [m_MapManager GetNextLocation:enemy.location];
								
								enemy.direction = [self GetDirectionFromLocation:enemy.location toLocation:enemy.nextLocation];
								switch (enemy.direction) 
								{
									case 1:
									{
										enemy.position.x += delta;
									}
										break;
									case 2:
									{
										enemy.position.y += delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 3:
									{
										enemy.position.y -= delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 4:
									{
										enemy.position.x -= delta;
									}
										break;
									default:
										break;
								}
							}
						}
					}
						break;
					case 4:
					{
						enemy.position = ccp(enemy.position.x - speed, enemy.position.y);
						//enemy.position.x += enemy.speed;
						if (enemy.position.x <= ([self GetPos:enemy.nextLocation].x) ) 
						{
							Location *endloc = [m_MapManager GetEnd];
							if (enemy.nextLocation.x == endloc.x && enemy.nextLocation.y == endloc.y) 
							{
								enemy.status = 1;
							}
							else
							{
								float delta = ([self GetPos:enemy.nextLocation].x) - enemy.position.x;
								enemy.position = [self GetPos:enemy.nextLocation];
								enemy.location = enemy.nextLocation;
								enemy.nextLocation = [m_MapManager GetNextLocation:enemy.location];
								
								enemy.direction = [self GetDirectionFromLocation:enemy.location toLocation:enemy.nextLocation];
								switch (enemy.direction) 
								{
									case 1:
									{
										enemy.position.x += delta;
										
									}
										break;
									case 2:
									{
										enemy.position.y += delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 3:
									{
										enemy.position.y -= delta;
										[m_Map reorderChild:enemy z:(LAYER_ITEM_ENEMY + 3*enemy.nextLocation.y)];
									}
										break;
									case 4:
									{
										enemy.position.x -= delta;
									}
										break;
									default:
										break;
								}
							}
						}
					}
						break;
					default:
						break;
				}
				
				if(__DirectionTemp != enemy.direction)
				{
					
					[self EnemyMoveActionChange:enemy EnemyKind:enemy.typeName state:0];
					
					
					
					
				}
				
			}
			
			//被定住了,效果逻辑
			else
			{
				enemy.stopTime--;
				if (enemy.stopTime <= 0) 
				{
					enemy.isStop = NO;
				}
			}

			
			//方向 1右边   2上边   3下边     4左边
			
		}
		
		//血量小于0,或者到了终点
		else 
		{
			//小兵死了
			if (enemy.hp <= 0) 
			{
				
				if(enemy.status != DeadBody && enemy.status != RotBody)
				{
				
					[self EnemyMoveActionChange:enemy EnemyKind:enemy.typeName state:1];
#ifndef __CLOSESOUND
					[[CGameSoundPlayW GameSoundPlayShare] SetSoundVolume:(enemy.typeName+1) SoundVolume:1.0];

					
					NSNumber * numNS = [NSNumber numberWithInt:(enemy.typeName+1)];
					BOOL b_add = true;
					for(int i=0;i<[__DeadEnemy count];i++)
					{
						if([[__DeadEnemy objectAtIndex:i] intValue] == enemy.typeName+1)
						{
							b_add = false;
							break;
						}

					}
					if(b_add)
					{
						[__DeadEnemy addObject:numNS];
						NSLog(@"enemyDead play Sound ID:%d",[numNS intValue]);
					
						[self schedule:@selector(MusicBack) interval:3.0f];
					}

#endif
					
					float tmoney = enemy.money;
					//是否增加金钱
					if ([self IsMoneyUp:enemy]) 
					{
						tmoney += tmoney;
					}
					m_Money += tmoney;
					m_Warrior.exp += enemy.exp;
					m_Exploit += enemy.exploit;
					enemy.status = DeadBody;
				}
				else if(enemy.status == DeadBody)
				{
					enemy.rotBodyTime++;
					//CCAction * pAct = [enemy getActionByTag:enemy.idStr];
					//检测死亡动画是否播放完,播放完删除敌兵
					if(enemy.rotBodyTime >30)
					{
						[array addObject:enemy];
						enemy.status = RotBody;
					}

				}
				//m_WarriorExp += [[Parameter sharedParameter] expEnemy:]
			}
			
			//到了终点
			else 
			{
				if (m_LifeLeft > 0) 
				{
					m_LifeLeft--;
				}
				[array addObject:enemy];
			}
			
		}

	}
	
	//删去小兵
	for(Enemy* enemy in array)
	{
		[m_Map removeChild:enemy cleanup:YES];
		[m_EnemyList removeObject:enemy];
	}
	[array release];
}

-(void)MusicBack
{
#ifndef __CLOSESOUND
	if([__DeadEnemy count] != 0)
	{
		int m_id = [[__DeadEnemy objectAtIndex:0] intValue];
		[__DeadEnemy removeObjectAtIndex:0];
		NSLog(@"enemyDead MusicBack Sound ID:%d",m_id);
		[[CGameSoundPlayW GameSoundPlayShare] SetSoundVolume:m_id SoundVolume:0.01];
	}
	
#endif
}


-(void)TowerUpdate
{
	for (Tower* tower in m_TowerList) 
	{
		switch (tower.towerState) 
		{
			//搜索状态
			case TOWERSTATE_SEARCH:
			{
				tower.frame++;
				Enemy* target = nil;
				if (2 == tower.type) 
				{
					float minDistance = 10000000;
					BOOL bNotSlow = NO;
					for (Enemy *enemy in m_EnemyList) 
					{
						if (([self IsImpactCircle:tower.position range1:tower.range center2:enemy.position range2:enemy.range])) 
						{
							CGPoint point = [self GetPos:enemy.nextLocation];
							float deltaDis = fabsf(point.x - enemy.position.x + point.y - enemy.position.y);
							float dis = [m_MapManager GetNumber:enemy.nextLocation] * 48 +deltaDis;
							
							if (bNotSlow) 
							{
								if ((!(enemy.slowtime > 0)) && dis < minDistance) 
								{
									target = enemy;
									minDistance = dis;
								}
							}
							else 
							{
								if (!(enemy.slowtime > 0)) 
								{
									target = enemy;
									minDistance = dis;
									bNotSlow = YES;
								}
								else 
								{
									if (dis < minDistance) 
									{
										target = enemy;
										minDistance = dis;
									}
								}
							}
						}
					}
					tower.target = target;
				}
				else
				{
					if (m_EnemySelected
						&&[self IsImpactCircle:tower.position range1:tower.range center2:m_EnemySelected.position range2:m_EnemySelected.range]
						&& m_EnemySelected.hp > 0
						&& m_EnemySelected.status != 1) 
					{
						target = m_EnemySelected;
						tower.target = target;
					}
					
					else 
					{
						if (tower.target && tower.target.hp > 0 && tower.target.status != 1 && [self IsImpactCircle:tower.position range1:tower.range center2:tower.target.position range2:tower.target.range]) 
						{
							target = tower.target;
						}
						else 
						{
							float minDistance = 1000000;
							for(Enemy* enemy in m_EnemyList) 
							{
								
								if (([self IsImpactCircle:tower.position range1:tower.range center2:enemy.position range2:enemy.range])) 
								{
									CGPoint point = [self GetPos:enemy.nextLocation];
									float deltaDis = fabsf(point.x - enemy.position.x + point.y - enemy.position.y);
									float dis = [m_MapManager GetNumber:enemy.nextLocation] * 48 +deltaDis;
									if (dis < minDistance) 
									{
										target = enemy;
										minDistance = dis;
									}
								}
							}
							tower.target = target;
						}
					}

					
					
					
					
					
				}
				
				if (target) 
				{
					float enemyDegree = GetDegree(target.position.x - tower.position.x, target.position.y - tower.position.y);
					if (GetAbsDegree(enemyDegree, tower.myDegree) < tower.attackDegree) 
					{
						tower.towerState = TOWERSTATE_ATTACK;
						tower.attackAniFrame = 0;
						
					}
					else 
					{
						tower.clockOrWise = ClockOrWiseClock(tower.myDegree, enemyDegree);
						tower.towerState = TOWERSTATE_TURN;
					}

					
				}
				
				
				
			}
				break;
				
			//转动状态
			case TOWERSTATE_TURN:
			{
				tower.frame++;
				if (tower.target.hp <= 0 
					|| tower.target.status == 1 
					|| !([self IsImpactCircle:tower.position range1:tower.range center2:tower.target.position range2:tower.target.range])) 
				{
					tower.towerState = TOWERSTATE_SEARCH;
				}
				else 
				{
					float enemyDegree = GetDegree(tower.target.position.x - tower.position.x, tower.target.position.y - tower.position.y);
					tower.clockOrWise = ClockOrWiseClock(tower.myDegree, enemyDegree);
					tower.flipX = IsNeedFlipX(tower.myDegree);
					
					
					switch (tower.clockOrWise) 
					{
						case 1:
						{
							tower.myDegree -= tower.turnSpeed;
							if (tower.myDegree < 0) 
							{
								tower.myDegree += 360.f;
							}
							
						}
							break;
						case 2:
						{
							tower.myDegree += tower.turnSpeed;
							if (tower.myDegree > 360) 
							{
								tower.myDegree -= 360.f;
							}
						}
							break;
						default:
							break;
					}
					[tower SetRectFromArea:GetAreaFromDegree(tower.myDegree)];
					//[tower setTextureRect:m_TowerRectInResource[GetAreaFromDegree(tower.myDegree)]];
					
			
					if (GetAbsDegree(enemyDegree, tower.myDegree) < tower.attackDegree
						&& tower.frame >= tower.interval) 
					{
						tower.towerState = TOWERSTATE_ATTACK;
						tower.attackAniFrame = 0;
					}
					
					
				}
				 
				
				
			}
				break;
				
			//攻击状态
			case TOWERSTATE_ATTACK:
			{
				
				if (0 == tower.attackAniFrame) 
				{
					[tower changeToAttack];
				}
				
				tower.attackAniFrame++;
				
				if (tower.attackAniFrame >= tower.attackAniLastTime) 
				{
					[tower changeToNormal];
					tower.attackAniFrame = 0;
					tower.frame = 0;
					
					Bullet* bullet = [Bullet bulletByType:tower.type level:tower.level];
					float deltaAttack = [self AttackPowerUp:tower];
					
					switch (tower.type) 
					{
						case 1:
						{
							bullet.target = tower.target;
							bullet.start = tower.position;
							bullet.end = tower.target.position;
						}
							break;
						case 2:
						{
							bullet.target = tower.target;
							bullet.start = tower.position;
							bullet.end = tower.target.position;
						}
							break;
						case 3:
						{
							bullet.start = tower.position;
							bullet.end = tower.target.position;
						}
							break;
						case 4:
						{
							bullet.start = tower.position;
							bullet.end = tower.target.position;
						}
							break;
						default:
							break;
					}
					
					bullet.dx = (bullet.end.x - bullet.start.x)/bullet.frame;
					bullet.dy = (bullet.end.y - bullet.start.y)/bullet.frame;
					bullet.position = tower.position;
					
					bullet.attack += deltaAttack;
					[m_Bullet addObject:bullet];
					[m_Map addChild:bullet z:20];
					tower.frame = 0;
					
					if (tower.target.hp <= 0 
						|| tower.target.status == 1 
						|| !([self IsImpactCircle:tower.position range1:tower.range center2:tower.target.position range2:tower.target.range]))
					{
						tower.towerState = TOWERSTATE_SEARCH;
						
					}
					else 
					{
						tower.towerState = TOWERSTATE_TURN;
					}

				}
			}
				break;
			default:
				break;
		}
	}
}




-(void)TowerFire
{
	for (Tower* tower in m_TowerList) 
	{
		tower.frame++;
		if (tower.frame >= tower.interval) 
		{
			Enemy* target = nil;
			
			if (2 == tower.type) 
			{
				float minDistance = 10000000;
				BOOL bNotSlow = NO;
				for (Enemy *enemy in m_EnemyList) 
				{
					if (([self IsImpactCircle:tower.position range1:tower.range center2:enemy.position range2:enemy.range])) 
					{
						CGPoint point = [self GetPos:enemy.nextLocation];
						float deltaDis = fabsf(point.x - enemy.position.x + point.y - enemy.position.y);
						float dis = [m_MapManager GetNumber:enemy.nextLocation] * 48 +deltaDis;
						
						if (bNotSlow) 
						{
							if ((!(enemy.slowtime > 0)) && dis < minDistance) 
							{
								target = enemy;
								minDistance = dis;
							}
						}
						else 
						{
							if (!(enemy.slowtime > 0)) 
							{
								target = enemy;
								minDistance = dis;
								bNotSlow = YES;
							}
							else 
							{
								if (dis < minDistance) 
								{
									target = enemy;
									minDistance = dis;
								}
							}
						}
					}
				}
				tower.target = target;
			}
			
			else
			{
				if (tower.target && tower.target.hp > 0 && tower.target.status != 1 && [self IsImpactCircle:tower.position range1:tower.range center2:tower.target.position range2:tower.target.range]) 
				{
					target = tower.target;
				}
				else 
				{
					float minDistance = 1000000;
					for(Enemy* enemy in m_EnemyList) 
					{
						
						if (([self IsImpactCircle:tower.position range1:tower.range center2:enemy.position range2:enemy.range])) 
						{
							CGPoint point = [self GetPos:enemy.nextLocation];
							float deltaDis = fabsf(point.x - enemy.position.x + point.y - enemy.position.y);
							float dis = [m_MapManager GetNumber:enemy.nextLocation] * 48 +deltaDis;
							if (dis < minDistance) 
							{
								target = enemy;
								minDistance = dis;
							}
						}
					}
					tower.target = target;
				}
			}

			if (target) 
			{
				Bullet* bullet = [Bullet bulletByType:tower.type level:tower.level];
				float deltaAttack = [self AttackPowerUp:tower];
				
				switch (tower.type) 
				{
					case 1:
					{
						bullet.target = target;
						bullet.start = tower.position;
						bullet.end = target.position;
					}
						break;
					case 2:
					{
						bullet.target = target;
						bullet.start = tower.position;
						bullet.end = target.position;
					}
						break;
					case 3:
					{
						bullet.start = tower.position;
						bullet.end = target.position;
					}
						break;
					case 4:
					{
						bullet.start = tower.position;
						bullet.end = target.position;
					}
						break;
					default:
						break;
				}
				
				bullet.dx = (bullet.end.x - bullet.start.x)/bullet.frame;
				bullet.dy = (bullet.end.y - bullet.start.y)/bullet.frame;
				bullet.position = tower.position;
				
				bullet.attack += deltaAttack;
				[m_Bullet addObject:bullet];
				[m_Map addChild:bullet z:20];
				tower.frame = 0;
			}
			
		}
	}
}
-(float)AttackPowerUp:(Tower*)tower
{
	float max = 0;
	for(Tower* power in m_PowerUpTower)
	{
		if([self IsImpactCircle:tower.position range1:tower.range center2:power.position range2:power.range])
		{
			if ([[Parameter sharedParameter] attackUpZhangu:power.level] > max) 
			{
				max = [[Parameter sharedParameter] attackUpZhangu:power.level];
			}
		}
	}
	return max;
}


-(Location*)GetLocation:(CGPoint)point
{
	int height = 0;
	if (0 == [m_MapManager GetType]) 
	{
		height = 480;
	}
	else 
	{
		height = 576;
	}

	int x = point.x;
	int y = height - point.y;
	x = x/48;
	y = y/48;
	return [Location LocationMake:x y:y];
}

//得到格子中点坐标
-(CGPoint)GetPos:(Location*)loc
{
	int height = 0;
	if (0 == [m_MapManager GetType]) 
	{
		height = 480;
	}
	else 
	{
		height = 576;
	}
	
	return CGPointMake((loc.x + 0.5)*48, height - (loc.y + 0.5)*48);
}


//坐标转换
-(CGPoint)ConvertToMap:(CGPoint)point
{
	
	int halfheight = 0;
	int halfwidth = 0;
	if (0 == [m_MapManager GetType]) 
	{
		halfheight = 240;
		halfwidth = 360;
	}
	else 
	{
		halfheight = 288;
		halfwidth = 432;
	}
	
	CGPoint mapPositon = m_Map.position;
	float scale = m_Map.scaleX;
	
	float Dx = point.x - mapPositon.x;
	float Dy = point.y - mapPositon.y;
	
	float X = halfwidth + Dx/scale;
	float Y = halfheight + Dy/scale;
	return CGPointMake(X, Y);
}

//读取波此文件
-(void)LoadWaveFile:(const char*) filename
{
	int i = 0;
	int line = 0;
	
	char rd[100][16];
	while (1) 
	{
		NSMutableArray *array = [[NSMutableArray alloc] init];
		memset(rd, 0, sizeof(rd));
		readcsv(filename, ';', 100, line, &rd[0][0], 16);
		if (0 == rd[0][0]) 
		{
			break;
		}
		
		for (i = 0; i < 50; i++) 
		{
			if (0 == rd[2*i][0]) 
			{
				break;
			}
			int frame = atoi(rd[2*i]);
			int type = atoi(rd[2*i + 1]);
			EnemyEnter * enter = [EnemyEnter EnemyEnterMake:frame type:type];
			[array addObject:enter];
			//[enter release];
		}
		
		[m_EnemyWave addObject:array];
		[array release];
		
		line++;
	}
}

-(void)WaveUpdate
{
	if ((unsigned int)m_WaveNum >= [m_EnemyWave count]) 
	{
		return;
	}
	if ((unsigned int)m_IndexInWave >= [[m_EnemyWave objectAtIndex:m_WaveNum] count]) 
	{
		
		if (0 == [m_EnemyList count]) 
		{
			m_WaveNum++;
			if ((unsigned int)m_WaveNum >= [m_EnemyWave count])
			{
				return;
			}
			else
			{
				m_IndexInWave = 0;
				EnemyEnter *enter = [[m_EnemyWave objectAtIndex:m_WaveNum] objectAtIndex:m_IndexInWave];
				m_WaveInterval = enter.interval;
			}
		}
		else
		{
			return;
		}
	}
	
	
	m_WaveInterval--;
	if (m_WaveInterval <= 0) 
	{
		EnemyEnter *enter = [[m_EnemyWave objectAtIndex:m_WaveNum] objectAtIndex:m_IndexInWave];
		[self addEnemy:enter.type];
		m_IndexInWave++;
		if ((unsigned int)m_IndexInWave < [[m_EnemyWave objectAtIndex:m_WaveNum] count]) 
		{
			EnemyEnter *enter1 = [[m_EnemyWave objectAtIndex:m_WaveNum] objectAtIndex:m_IndexInWave];
			m_WaveInterval = enter1.interval;
		}
		return;
	}
}

-(int)GetDirectionFromLocation:(Location*) loc1 toLocation:(Location*)loc2
{
	if(loc1.x == loc2.x)
	{
		if(loc1.y < loc2.y)
		{
			return 3;
		}
		else 
		{
			return 2;
		}

	}
	if (loc1.y == loc2.y) 
	{
		if(loc1.x < loc2.x)
		{
			return 1;
		}
		else 
		{
			return 4;
		}
	}
	return 0;
}


-(void) BulletUpdate
{
	NSMutableArray *deletArray = [[NSMutableArray alloc] init];
	for (Bullet *bullet in m_Bullet) 
	{
		bullet.frame--;
		bullet.position = ccp(bullet.position.x + bullet.dx, bullet.position.y + bullet.dy);
		if (bullet.frame <= 0) 
		{
			switch (bullet.type) 
			{
				case 1:
				{
					if (bullet.target.hp > 0 && 1 != bullet.target.status) 
					{
						bullet.target.hp -= bullet.attack;
					}
					[deletArray addObject:bullet];
				}
					break;
				case 2:
				{
					if (bullet.target.hp > 0 && 1 != bullet.target.status) 
					{
						bullet.target.hp -= bullet.attack;
						bullet.target.slowdown = bullet.slowdown;
						bullet.target.slowtime = bullet.slowFrame;
					}
					[deletArray addObject:bullet];
					
				}
					break;
				case 3:
				{
					[self LineHurtFromStart:bullet.start toEnd:bullet.end withAttack:bullet.attack];
					[deletArray addObject:bullet];
				}
					break;
				case 4:
				{
					[self AreaHurtAtPoint:bullet.end withRange:bullet.range andAttack:bullet.attack];
					[deletArray addObject:bullet];
				}
					break;
				default:
					break;
			}
		}
		
	}
	for (Bullet *bullet in deletArray) 
	{
		[m_Bullet removeObject:bullet];
		[m_Map removeChild:bullet cleanup:YES];
	}
}




//碰撞算法
//圆碰撞
-(BOOL) IsImpactCircle:(CGPoint)center1 range1:(float)range1 center2:(CGPoint)center2 range2:(float)range2
{
	float distance = (center1.x - center2.x)*(center1.x - center2.x) + (center1.y - center2.y)*(center1.y - center2.y);
	if(distance < (range1 + range2)*(range1 + range2) ) 
	{
		return YES;
	}
	else 
	{
		return NO;
	}

}


//范围伤害
-(void) AreaHurtAtPoint:(CGPoint)pos withRange:(int)range andAttack:(float)attack
{
	for(Enemy* enemy in m_EnemyList)
	{
		if([self IsImpactCircle:enemy.position range1:enemy.range center2:pos range2:range])
		{
			enemy.hp -= attack;
		}
	}
}

//穿刺伤害
-(void) LineHurtFromStart:(CGPoint)point1 toEnd:(CGPoint)point2 withAttack:(float)attack
{
	for(Enemy* enemy in m_EnemyList)
	{
		if([self DistanceLineWithPoints:point1 point2:point2 toPoint:enemy.position] < enemy.range)
		{
			enemy.hp -= attack;
		}
	}
}


-(float) DistanceLineWithPoints:(CGPoint)point1 point2:(CGPoint)point2 toPoint:(CGPoint)point3
{
	float x1 = point1.x - point2.x;
	float y1 = point1.y - point2.y;
	float x2 = point1.x - point3.x;
	float y2 = point1.y - point3.y;
	float length = sqrtf(x1*x1 + y1*y1);
	return (fabsf(x1*y2 - y1*x2))/length;
	
}

/*武将相关方法*/

//武将刷新
-(void) WarriorUpdate
{
	//状态显示
	CCLabel *levelLabel = (CCLabel*)[m_Warrior getChildByTag:kWarriorLevel];
	NSString *levelStr = [NSString stringWithFormat:@"%d", m_Warrior.level];
	[levelLabel setString:levelStr];
	
	CCLabel *levelState = (CCLabel*)[m_Warrior getChildByTag:kWarriorState];
	NSString *stateStr = [NSString stringWithFormat:@"%d", m_Warrior.state];
	[levelState setString:stateStr];
	
	if (m_Warrior.exp >= m_Warrior.levelExp) 
	{
		[m_Warrior levelUp];
		m_Warrior.exp -= m_Warrior.levelExp;
	}
	
	
	m_Warrior.frame--;
	
	if (m_Warrior.frame > 0) 
	{
		return;
	}
	
	switch (m_Warrior.state) {
		case WARRIOR_STAND:
		{
			if([__touchSkillArray count]>0)//有技能施法
			{
				[self WarriorSkillEffect];
				return;
			}
			
			m_Warrior.target = [self WarriorFindTarget];
			if (m_Warrior.target != nil) 
			{
				Location *targetloc = [self GetLocation:m_Warrior.target.position];
				m_Warrior.end = targetloc;
				[targetloc release];
				[m_MapManager MarkWarriorMap:m_Warrior.end];
				[m_MapManager CopyBack];
				//m_Warrior.state = WARRIOR_ATTACK;
				//__attackKind = Normal_Attack;
				[self ChangeGuanAttackDirect];
				[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_STAND newAction:WARRIOR_ATTACK];
			}
		}
			break;
		case WARRIOR_RUN:
		{
			[self WarriorRun];
			
		}
			
			break;
		case WARRIOR_ATTACK:
		{
			
			BOOL bIsAttackOver = [self IsGuanAttackOver:__attackKind];
			if(!bIsAttackOver)//攻击动画结束
			{
				return;
			}
			if(__attackKind == Fire_Attack)
				[self HuoqiangFire];
			
			[self GuanYuAttackOver];

		}
			break;
			
		case WARRIOR_SHIFA:
		{
			if([self IsGuanDoSkillOver])
			{
				//[self ChangeGuanAttackDirect];
				[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_SHIFA newAction:WARRIOR_STAND];
			}
		}
			
		default:
			break;
	}
}

-(id) WarriorFindTarget
{
	Enemy *target = nil;
	
	float minDistance = 1000000;
	for(Enemy* enemy in m_EnemyList) 
	{
		
		if (([self IsImpactCircle:m_Warrior.position range1:m_Warrior.guardRadius center2:enemy.position range2:enemy.range])) 
		{
			if(enemy.hp <=0)
				return nil;
			
			CGPoint point = [self GetPos:enemy.nextLocation];
			float deltaDis = fabsf(point.x - enemy.position.x + point.y - enemy.position.y);
			float dis = [m_MapManager GetNumber:enemy.nextLocation] * 48 +deltaDis;
			if (dis < minDistance) 
			{
				target = enemy;
				minDistance = dis;
			}
		}
	}
	return target;
}




-(void) WarriorRun
{
	float speed = m_Warrior.speed;
	//当前enemy方向的副本
	int __DirectionTemp = m_Warrior.direction;
	switch (m_Warrior.direction) {
		case 1:
		{
			m_Warrior.position = ccp(m_Warrior.position.x + speed, m_Warrior.position.y);
			if (m_Warrior.position.x >= ([self GetPos:m_Warrior.nextLocation].x) ) //武将位置大于下一步的X坐标
			{
				
				if (m_Warrior.nextLocation.x == m_Warrior.end.x && m_Warrior.nextLocation.y == m_Warrior.end.y) 
				{//武将位置为移动终点位置
					if (WARRIOR_RUN == m_Warrior.state) 
					{
						
						[self GuanRunStop:__DirectionTemp oldAction:WARRIOR_RUN newAction:WARRIOR_STAND];
						return;
						//m_Warrior.nextLocation = nil;
					}
				}
				else
				{
					//下一个移动点的X位移
					float delta = m_Warrior.position.x - ([self GetPos:m_Warrior.nextLocation].x);
					if(![self CheckGuanYuNextMove:delta])//判断是否能再移动
						return;
				}
			}
		}
			break;
		case 2:
		{
			m_Warrior.position = ccp(m_Warrior.position.x, m_Warrior.position.y + speed);
			if (m_Warrior.position.y >= ([self GetPos:m_Warrior.nextLocation].y) ) 
			{
				
				if (m_Warrior.nextLocation.x == m_Warrior.end.x && m_Warrior.nextLocation.y == m_Warrior.end.y) 
				{
					if (WARRIOR_RUN == m_Warrior.state) 
					{
						[self GuanRunStop:__DirectionTemp oldAction:WARRIOR_RUN newAction:WARRIOR_STAND];
						return;
					}
				}
				else
				{
					float delta = m_Warrior.position.y - ([self GetPos:m_Warrior.nextLocation].y);
					if(![self CheckGuanYuNextMove:delta])
						return;
					
				}
				
			}
		}
			break;
		case 3:
		{
			//enemy.position.y -= enemy.speed;
			m_Warrior.position = ccp( m_Warrior.position.x, m_Warrior.position.y - speed );
			if (m_Warrior.position.y <= ([self GetPos:m_Warrior.nextLocation].y) ) 
			{
				
				if (m_Warrior.nextLocation.x == m_Warrior.end.x && m_Warrior.nextLocation.y == m_Warrior.end.y) 
				{
					if (WARRIOR_RUN == m_Warrior.state) 
					{
						[self GuanRunStop:__DirectionTemp oldAction:WARRIOR_RUN newAction:WARRIOR_STAND];
						return;
					}
				}
				else
				{
					float delta = ([self GetPos:m_Warrior.nextLocation].y) - m_Warrior.position.y;
					if(![self CheckGuanYuNextMove:delta])
						return;
	
				}
			}
		}
			break;
		case 4:
		{
			m_Warrior.position = ccp(m_Warrior.position.x - speed, m_Warrior.position.y);
			if (m_Warrior.position.x <= ([self GetPos:m_Warrior.nextLocation].x) ) 
			{
				
				if (m_Warrior.nextLocation.x == m_Warrior.end.x && m_Warrior.nextLocation.y == m_Warrior.end.y) 
				{
					if (WARRIOR_RUN == m_Warrior.state) 
					{
						[self GuanRunStop:__DirectionTemp oldAction:WARRIOR_RUN newAction:WARRIOR_STAND];
						return;
					}
				}
				else
				{
					float delta = ([self GetPos:m_Warrior.nextLocation].x) - m_Warrior.position.x;
					if(![self CheckGuanYuNextMove:delta])
						return;
				}
			}
		}
			break;
		default:
			break;
	}
	__apertureSpr.position = m_Warrior.position;
	//改变英雄的方向
	if(__DirectionTemp != m_Warrior.direction)
	{
		[self ChangeWarrirDirection:__DirectionTemp oldKind:GUAN_PAO_LEFT actionKind:GUAN_PAO_LEFT];
	}
}

/*武将技*/

//触发技能
-(void) PutEffect:(int) type  usePoint:(CGPoint)uPoint;
{
	if (SKILL_BAGUA == type) 
	{
		EffectBaGua *bagua = [EffectBaGua bagua];
		bagua.position = uPoint;
		[m_BaGuaEffect addObject:bagua];
//		[m_Map addChild:bagua z:0];
		[self BaGuaAction:bagua];
		[self PlaySkill:uPoint];
		return;
	}
	else if (SKILL_LUOLEI == type) 
	{
		EffectLuoLei *luolei = [EffectLuoLei luolei:m_Warrior.level];
		luolei.position = uPoint;
		//[m_LuoLeiEffect addObject:luolei];
		[self PlaySkill:uPoint];
		[self LuoLeiEffect:luolei];
		return;
	}
	else if (SKILL_TOUQU == type) 
	{
		EffectTouQu *touqu = [EffectTouQu touqu];
		touqu.position = uPoint;
		[m_TouQuEffect addObject:touqu];
		[self PlaySkill:uPoint];
		return;
	}
	else if (SKILL_HUOQIANG == type) 
	{
		
		return;
	}
	return;
}

//技能效果刷新
-(void) EffectUpdate
{
	NSMutableArray *delBaGua = [[NSMutableArray alloc] initWithCapacity:5];
	NSMutableArray *delTouQu = [[NSMutableArray alloc] initWithCapacity:5];
	NSMutableArray *delLuoLei = [[NSMutableArray alloc] initWithCapacity:5];
	
	
	for (EffectBaGua* bagua in m_BaGuaEffect) 
	{
		bagua.lastTime--;
		if (bagua.lastTime <= 0) 
		{
			[delBaGua addObject:bagua];
		}
	}
	
	for (EffectTouQu* touqu in m_TouQuEffect)
	{
		touqu.lastTime--;
		if (touqu.lastTime <= 0) 
		{
			[delTouQu addObject:touqu];
		}
	}
	
	for(EffectLuoLei* luolei in m_LuoLeiEffect)
	{
		luolei.takeTime--;
		if (luolei.takeTime <= 0)
		{
			[self AreaHurtAtPoint:luolei.position withRange:luolei.range andAttack:luolei.attack];
			[delLuoLei addObject:luolei];
		}
	}
	
	
	//需要删除掉得特效处理
	for (EffectBaGua* delbagua in delBaGua) 
	{
		[m_BaGuaEffect removeObject:delbagua];
		[m_Map removeChild:delbagua cleanup:YES];
	}
	
	for (EffectBaGua* deltouqu in delTouQu) 
	{
		[m_TouQuEffect removeObject:deltouqu];
		[m_Map removeChild:deltouqu cleanup:YES];
	}
	
	for (EffectLuoLei* delluolei in delLuoLei) 
	{
		[m_LuoLeiEffect removeObject:delluolei];
		[m_Map removeChild:delluolei cleanup:YES];
	}
	
	//临时数组释放
	[delBaGua release];
	[delTouQu release];
	[delLuoLei release];
}

//八卦阵对小兵速度影响参数
-(void) BaGuaAction:(EffectBaGua *) bagua
{
	for (Enemy* enemy in m_EnemyList) 
	{
		if([self IsImpactCircle:enemy.position range1:enemy.range center2:bagua.position range2:bagua.range])
		{
			//enemy.isStop = YES;
			enemy.stopTime = [[Parameter sharedParameter] baGuaLastTime];
		}
	}
	return;
}

//偷取术
-(BOOL) IsMoneyUp:(Enemy *) enemy
{
	BOOL up = NO;
	for (EffectTouQu* effect in m_TouQuEffect) 
	{
		if ([self IsImpactCircle:enemy.position range1:enemy.range center2:effect.position range2:effect.range])
		{
			up = YES;
			break;
		}
	}
	return up;
}







// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	[m_MapManager release];
	[m_EnemyList release];
	[m_Bullet release];
	[m_TowerList release];
	[m_PowerUpTower release];
	
	[m_EnemyWave release];
	
	[__touchSkillArray release];
	
	[m_Warrior release];
	
	[__skillFireArray release];
	[__touchLocArray release];
	
	//触控图标, 金钱显示
	//金钱显示
	[m_MoneyLabel release];
	
	//放塔的图标
	//普通箭塔图标
	[m_IconArrow release];
	
	//毒刺塔图标
	[m_IconPoison release];
	
	//穿刺塔图标
	[m_IconPuncture release];
	
	//投石机图标
	[m_IconMangonel release];
	
	//战鼓台图标
	[m_IconPowerUpTower release];
	
	[__guanActionArray release];
	[__DeadEnemy release];
	
	// don't forget to call "super dealloc"
	[super dealloc];
}

////////////////waver code form 2010/8/4
#pragma mark parse Editor bin file----waver code 2010/8/4
-(void) EnemyMoveActionChange:(Enemy *) pEnemy EnemyKind:(int)Type state:(int)kind
{
	try
	{
		int direction = pEnemy.direction;
		
		int anidir = [self GetEnemyMoveActionIndex:direction];
		//对应的解析文件tag
		int file_tag;
		//动画是否循环播放
		BOOL b_cyc = true;
		if(kind == 0)
		{
			file_tag= [self GetMoveBinTag:Type];
			//file_tag = [self GetDeadBinTag:Type];
		}
		else
		{
			file_tag = [self GetDeadBinTag:Type];
			b_cyc = false;
		}
		
		CCAnimation * animation = [m_Editor CreateAnimation:anidir doubleTime:AccelerateNum fileTag:file_tag];
		
		[pEnemy stopAllActions];
		
		[pEnemy runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:b_cyc]]];
//		CCAction * pAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:b_cyc]];
//		[pEnemy runAction:pAction];
	}
	catch (NSException * myException)
	{
		
	}
}

-(void) InitCAnimationStore
{
	//初始化动画编辑器动画
	m_Editor = [CAnimationStoreW ShareAnimationStore];
	//动画小兵
	[m_Editor AddEditorFile:@"bubingpaodong.bin" EditorKind:SINGLELEMENT Tag:BUBINGPAODONG];
	[m_Editor AddEditorFile:@"bubingsiwang.bin" EditorKind:SINGLELEMENT Tag:BUBINGSIWANG];
	[m_Editor AddEditorFile:@"mengsiwang.bin" EditorKind:SINGLELEMENT Tag:MENGSIWANG];
	[m_Editor AddEditorFile:@"mengzoudong.bin" EditorKind:SINGLELEMENT Tag:MENGZOUDONG];
	[m_Editor AddEditorFile:@"qingpaodong.bin" EditorKind:SINGLELEMENT Tag:QINGPAODONG];
	[m_Editor AddEditorFile:@"qingsiwang.bin" EditorKind:SINGLELEMENT Tag:QINGSIWANG];
	[m_Editor AddEditorFile:@"tengpaodong.bin" EditorKind:SINGLELEMENT Tag:TENGPAODONG];
	[m_Editor AddEditorFile:@"tengsiwang.bin" EditorKind:SINGLELEMENT Tag:TENGSIWANG];
	[m_Editor AddEditorFile:@"tiesiwang.bin" EditorKind:SINGLELEMENT Tag:TIESIWANG];
	[m_Editor AddEditorFile:@"tieyidong.bin" EditorKind:SINGLELEMENT Tag:TIEYIDONG];
	[m_Editor AddEditorFile:@"xiangsiwang.bin" EditorKind:SINGLELEMENT Tag:XIANGSIWANG];
	[m_Editor AddEditorFile:@"xiangzoudong.bin" EditorKind:SINGLELEMENT Tag:XIANGZOUDONG];
	[m_Editor AddEditorFile:@"zhanpaodong.bin" EditorKind:SINGLELEMENT Tag:ZHANPAODONG];
	[m_Editor AddEditorFile:@"zhansiwang.bin" EditorKind:SINGLELEMENT Tag:ZHANSIWANG];
	[m_Editor AddEditorFile:@"zhongpaodong.bin" EditorKind:SINGLELEMENT Tag:ZHONGPAODONG];
	[m_Editor AddEditorFile:@"zhongsiwang.bin" EditorKind:SINGLELEMENT Tag:ZHONGSIWANG];
	
	//动画关羽
	[m_Editor AddEditorFile:@"guandaiji.bin" EditorKind:MUTELEMENT Tag:GUANYUWAIT];
	[m_Editor AddEditorFile:@"guanpao.bin" EditorKind:MUTELEMENT Tag:GUANYUPAO];
	[m_Editor AddEditorFile:@"guankan.bin" EditorKind:MUTELEMENT Tag:GUANYUHIT];
	[m_Editor AddEditorFile:@"guanshifa.bin" EditorKind:MUTELEMENT Tag:GUANYUSHIFA];
	[m_Editor AddEditorFile:@"bagua01.bin" EditorKind:MUTELEMENT Tag:GUANYUBAGUAONE];
	[m_Editor AddEditorFile:@"bagua02.bin" EditorKind:MUTELEMENT Tag:GUANYUBAGUATWO];
	[m_Editor AddEditorFile:@"huoqiang.bin" EditorKind:MUTELEMENT Tag:GUANYUHUOQIANG];
	[m_Editor AddEditorFile:@"leiji01.bin" EditorKind:MUTELEMENT Tag:GUANYULEIJIONE];
	[m_Editor AddEditorFile:@"leiji02.bin" EditorKind:MUTELEMENT Tag:GUANYULEIJITWO];
	[m_Editor AddEditorFile:@"penhuo.bin" EditorKind:MUTELEMENT Tag:GUANYUPENHUO];
	[m_Editor AddEditorFile:@"touqu01.bin" EditorKind:MUTELEMENT Tag:GUANYUTOUQUONE];
	[m_Editor AddEditorFile:@"touqu02.bin" EditorKind:MUTELEMENT Tag:GUANYUTOUQUTWO];

	//动画特效
	[m_Editor AddEditorFile:@"texiao01.bin" EditorKind:MUTELEMENT Tag:ENABLE_POINT];
	[m_Editor AddEditorFile:@"texiao02.bin" EditorKind:MUTELEMENT Tag:DISABLE_POINT];
	[m_Editor AddEditorFile:@"texiao03.bin" EditorKind:MUTELEMENT Tag:WARRIR_UP];
	[m_Editor AddEditorFile:@"texiao04.bin" EditorKind:MUTELEMENT Tag:TOUSHI_HIT];
}


-(int)GetEnemyMoveActionIndex:(int) direction
{
	//获取脚色方位对应的动画编辑器上的动画序列
	int anidir = 0;
	switch (direction) 
	{
		case 1:
		{
			anidir = 1;
		}
			break;
		case 2:
		{
			anidir = 2;
		}
			break;
		case 3:
		{
			anidir = 3;
		}
			break;
		case 4:
		{
			anidir = 0;
		}
			break;
		default:
			break;
	}
	return anidir;
}

-(int)	GetMoveBinTag:(int)enemyType
{
	//图片TAG
	switch (enemyType) 
	{
		case FOOT_MAN:
			return BUBINGPAODONG;
			break;
		case TENGJIA_MAN:
			return TENGPAODONG;
			break;
		case CAVALRY:
			return QINGPAODONG;
			break;
		case MAN_AT_ARMS:
			return ZHONGPAODONG;
			break;
		case ELEPHANT_MAN:
			return XIANGZOUDONG;
			break;
		case TANK:
			return ZHANPAODONG;
			break;
		case IRON_TANK:
			return TIEYIDONG;
			break;
		default:
			break;
	}
	
	NSException * myException = [NSException 
								 exceptionWithName:@"GetMoveBinTag" reason:@"input EnemyType is  invalid" userInfo:nil];
	throw myException;
}

-(int) GetDeadBinTag:(int)enemyType
{
	switch (enemyType) 
	{
		case FOOT_MAN:
			return BUBINGSIWANG;
			break;
		case TENGJIA_MAN:
			return TENGSIWANG;
			break;
		case CAVALRY:
			return QINGSIWANG;
			break;
		case MAN_AT_ARMS:
			return ZHONGSIWANG;
			break;
		case ELEPHANT_MAN:
			return XIANGSIWANG;
			break;
		case TANK:
			return ZHANSIWANG;
			break;
		case IRON_TANK:
			return TIEYIDONG;
			break;
		default:
			break;
	}
	
	NSException * myException = [NSException 
								 exceptionWithName:@"GetMoveBinTag" reason:@"input EnemyType is  invalid" userInfo:nil];
	throw myException;
}

#pragma mark Enemy Control

#pragma mark ImageLoading 
//加载图片
-(void)LoadImage
{
	//加载图片
	[[CCTextureCache sharedTextureCache] addImageAsync:@"bubing.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"menghuo.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"qingqibing.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"tengjia.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"tiejiazhanche.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"xiangbing.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"zhanche.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"zhongqishi.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"ChangBan.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"DingShan.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"HuLao.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"Nanzhong.png" target:self selector:@selector(LoadPictureOver)];
	
	
	//[[CCTextureCache sharedTextureCache] addImageAsync:@"hulao.png" target:self selector:@selector(LoadPictureOver)];
//	[[CCTextureCache sharedTextureCache] addImageAsync:@"dingjun.png" target:self selector:@selector(LoadPictureOver)];
	//[[CCTextureCache sharedTextureCache] addImageAsync:@"changbanpo.png" target:self selector:@selector(LoadPictureOver)];
//	[[CCTextureCache sharedTextureCache] addImageAsync:@"nanzhong.png" target:self selector:@selector(LoadPictureOver)];
	
	
	//game Ui
	[[CCTextureCache sharedTextureCache] addImageAsync:@"HPtiao.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_hero01_fx_btn.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_num_back.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_num.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_num2.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_pause_btn_down.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_pause_btn.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_top_all2.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_tower01.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_tower02.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_tower03.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_tower04.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"iGUI_tower05.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"num_tada_an.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"num_tada.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"quan_G.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"quan_R.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"quanda_G.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"quanda_R.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"ta_LVL.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"taup_an_da.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"taup_da.png" target:self selector:@selector(LoadPictureOver)];
	

	//关羽图片
	[[CCTextureCache sharedTextureCache] addImageAsync:@"bagua01.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"bagua02.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"fire02.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"fire04.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"guan_master.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"horse01_master-1.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"horse01_master-2.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"kanheying.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"leiji01.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"leiji02.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"touqu01.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"touqu02.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"weapon01_master-1.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"weapon01_master-2.png" target:self selector:@selector(LoadPictureOver)];
	
	//特效动画
	[[CCTextureCache sharedTextureCache] addImageAsync:@"texiao_1dianji_db.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"texiao_2nodianji_db.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"texiao_3LVUP_db.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"toushi_4_db.png" target:self selector:@selector(LoadPictureOver)];
	
	//施法ICON
	[[CCTextureCache sharedTextureCache] addImageAsync:@"baonu.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"shifa.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"shifa2.png" target:self selector:@selector(LoadPictureOver)];
	[[CCTextureCache sharedTextureCache] addImageAsync:@"touqu2.png" target:self selector:@selector(LoadPictureOver)];
	

	[self unschedule:@selector(LoadImage)];
	
}

//每一个图片加载完后调用一次
-(void)LoadPictureOver
{
	loadImageNum++;
	if(loadImageNum == 48)
	{
		[self unschedule:@selector(LoadImage)];
		[self InitSprite];
		
#ifndef __CLOSESOUND
		
		[[CGameSoundPlayW GameSoundPlayShare]PlaySound:0];
		
		for(int i=1;i<(int)S_MAX;i++)
		{
			[[CGameSoundPlayW GameSoundPlayShare] PlaySound:i];
			[[CGameSoundPlayW GameSoundPlayShare] SetSoundVolume:i SoundVolume:0.01];
		}
		

#endif
		//[[CMutSoundPlayW MutSoundPlayShare]PlayGameSound];
		
		__DeadEnemy = [[NSMutableArray alloc]init];
		
	}
}

#pragma mark WeaponIcon----waver 2010-8-11
-(void)WeaponIconMove:(BOOL)b_back
{
	int Y = 100;
	if(b_back == NO)
		Y=-100;
	
	id actionOne = [CCMoveBy actionWithDuration:0.5 position:ccp(0,Y)];
	id actionTwo = [CCMoveBy actionWithDuration:0.5 position:ccp(0,Y)];
	id actionThree = [CCMoveBy actionWithDuration:0.5 position:ccp(0,Y)];
	id actionFour = [CCMoveBy actionWithDuration:0.5 position:ccp(0,Y)];
	id actionFive = [CCMoveBy actionWithDuration:0.5 position:ccp(0,Y)];

	[m_IconArrow runAction:[CCSequence actions:actionOne,nil]];
	[m_IconPoison runAction:[CCSequence actions:actionTwo,nil]];
	[m_IconPuncture runAction:[CCSequence actions:actionThree,nil]];
	[m_IconMangonel runAction:[CCSequence actions:actionFour,nil]];
	[m_IconPowerUpTower runAction:[CCSequence actions:actionFive,nil]];

}

-(void)MoveWeaponIconMap:(int)weaponName IsEnable:(BOOL)bIs
{
	m_TouchState = TOUCH_PUT_TOWER;

	m_PutTowerIcon = [[CCSprite spriteWithFile:[self WeaponPngName:weaponName]]retain];
	m_PutTowerIcon.position = ccp(1000, 1000);
	NSString*pStr;
	if(bIs)
		pStr = [NSString stringWithString:@"quan_G.png"];
	else
	{
		pStr = [NSString stringWithString:@"quan_R.png"];
	}

	CCSprite* fanwei = [CCSprite spriteWithFile:pStr];
	fanwei.position = ccp(24, 24);
	[fanwei setScale:([[Parameter sharedParameter] RadiusArrowWeapon:weaponName Level:1 ] / 75)];
	[fanwei setOpacity:100];
	[m_PutTowerIcon addChild:fanwei z:1];
	[m_PutTowerIcon setOpacity:100];
	[m_Map addChild:m_PutTowerIcon z:22];
}

-(NSString*)WeaponPngName:(int)weaponName;
{
	NSString * strPng;
	switch (weaponName) {
		case NormalWeapon:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower01.png"];
			break;
		}	
		case Poison:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower02.png"];

			break;
		}
		case Puncture:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower03.png"];

			break;
		}
		case Mangonel:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower04.png"];

			break;
		}
		case PowerUpTower:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower05.png"];
	
			break;
		}
		default:
		{
			strPng = [[NSString alloc] initWithString:@"iGUI_tower01.png"];

			break;
		}
	}
	return strPng;
}

-(int)WeaponPrice:(int)weaponName
{
	int price = 0;
	switch (weaponName) {
		case NormalWeapon:
		{
			price = [[Parameter sharedParameter] priceArrow:1];
			break;
		}	
		case Poison:
		{
			price = [[Parameter sharedParameter] pricePoison:1];
			break;
		}
		case Puncture:
		{
			price = [[Parameter sharedParameter] pricePuncture:1];
			break;
		}
		case Mangonel:
		{
			price = [[Parameter sharedParameter] priceMangonel:1];
			break;
		}
		case PowerUpTower:
		{
			price = [[Parameter sharedParameter] priceZhangu:1];
			break;
		}
		default:
		{
			price = [[Parameter sharedParameter] priceArrow:1];
			break;
		}
	}
	return price;
}

-(CGPoint)WeaponTouchPoint:(int)weaponName
{
	CGPoint weaponPoint;
	switch (weaponName) {
		case NormalWeapon:
		{
			weaponPoint = ccp(167+32, 320-252-32);
			break;
		}	
		case Poison:
		{
			weaponPoint = ccp(229+32, 320-252-32);
			
			break;
		}
		case Puncture:
		{
			weaponPoint = ccp(292+32, 320-252-32);
			break;
		}
		case Mangonel:
		{
			
			weaponPoint = ccp(352+32, 320-252-32);
			break;
		}
		case PowerUpTower:
		{
			
			weaponPoint = ccp(414+32, 320-252-32);
			break;
		}
		default:
		{
			weaponPoint = ccp(167+32, 320-252-32);
			break;
		}
	}
	return weaponPoint;
}


-(CCSprite*)AddWeaponIcon:(int)weaponName
{
	CGPoint weaponPoint = [self WeaponTouchPoint:weaponName];
	NSString * strPng = [[NSString alloc]initWithString:[self WeaponPngName:weaponName]];
//	int price = [self WeaponPrice:weaponName];
	CCSprite * iconSprite = [CCSprite spriteWithFile:strPng];
	CCSprite * priceBack = [CCSprite spriteWithFile:@"iGUI_num_back.png"];
	iconSprite.position = weaponPoint;
	priceBack.position = ccp(35+14,20-9);
	[iconSprite addChild:priceBack z:1 ];
	
	[strPng release];
	[self addChild:iconSprite z:1];
	
	return iconSprite;
}

#pragma mark GuanYu Animation -----waver 2010/8/16
//方向 1右边   2上边   3下边     4左边

-(void)InitGuanyuAnimation
{
	__guanActionArray = [[NSMutableDictionary alloc] init];
	[self CreateGuanMove:GUANYUWAIT beginTag:GUAN_WAIT_LEFT];
	[self CreateGuanMove:GUANYUPAO beginTag:GUAN_PAO_LEFT];
	[self CreateGuanMove:GUANYUHIT beginTag:GUAN_HIT_LEFT];
	[self CreateGuanMove:GUANYUSHIFA beginTag:GUAN_SHIFA_LEFT];
	[self CreateGuanMove:GUANYUHUOQIANG beginTag:GUAN_HUOQIANG_LEFT];
}

-(void)CreateGuanMove:(int)binName beginTag:(int)firstTag
{
	int tagIndex = 0;
	
	for(int i=0;i<4;i++)
	{
		BOOL isCyc = true;
		tagIndex = firstTag+i;
		if(tagIndex > 8)
		{
			isCyc = false;
		}
		CActionSpriteW * pTwo = [[CAnimationStoreW ShareAnimationStore] CreateActionSprite:
							  i doubleTime:AccelerateNum cyc:isCyc fileTag:binName];

		[pTwo StartPlay];
		[m_Warrior addChild:pTwo z:5 tag:tagIndex];
		[pTwo setVisible:NO];
		
		pTwo.position = CGPointMake(0, 10);
		
		[__guanActionArray setObject:pTwo forKey:[NSNumber numberWithInt:tagIndex]];

	}

}

-(void)ChangeWarrirDirection:(int)oldAction oldKind:(int)oldBegin actionKind:(int)kindBegin
{
	static int currentVisable = 0;
	//当前动画索引
	int oldDirect = [self GetEnemyMoveActionIndex:oldAction]+oldBegin;
	//新动画索引
	int newDirect = [self GetEnemyMoveActionIndex:m_Warrior.direction]+kindBegin;
	if(oldDirect <1 || newDirect <1||oldDirect > 20 ||newDirect >20)
	{
		NSException * myException = [NSException 
									 exceptionWithName:@"changeWarrirDirection" 
									 reason:@"warrir direction error!" userInfo:nil];
		@throw myException;
	}
	if(newDirect >= GUAN_HIT_LEFT)//攻击动画开始
	{
		[[__guanActionArray objectForKey:[NSNumber numberWithInt:newDirect]] StartPlay];
//		NSLog(@"ChangeWarrirDirection ---startPlay:%d",newDirect);
	}
	if(currentVisable != oldDirect)
	{
		if(currentVisable != 0)
		{
			oldDirect = currentVisable;
			//[MyExcetion ThorwException:@"changeWarr" resultStr:@"old is not old"];
		}
	}
	[[__guanActionArray objectForKey:[NSNumber numberWithInt:oldDirect]] setVisible:NO];
//	NSLog(@"ChangeWarrirDirection ---setVisibleNO:%d",oldDirect);
	
	[[__guanActionArray objectForKey:[NSNumber numberWithInt:newDirect]] setVisible:YES];
//	NSLog(@"ChangeWarrirDirection ---setVisibleYES:%d",newDirect);
	currentVisable = newDirect;
}



-(void)GuanRunStop:(int)oldDirect oldAction:(int)oldKind newAction:(int)newKind
{
	int oldKindBegin = oldKind * 4 + GUAN_WAIT_LEFT;
	int newKindBegin = newKind * 4 + GUAN_WAIT_LEFT;
	if(newKind == WARRIOR_SHIFA && m_SkillSelect == SKILL_HUOQIANG)
	{
		newKindBegin = newKindBegin+4;
	}
	else if(newKind == WARRIOR_ATTACK && __attackKind == Fire_Attack)
	{
		newKindBegin = newKindBegin+8;
		//[self HuoqiangFire];
	}
	[self ChangeWarrirDirection:oldDirect oldKind:oldKindBegin actionKind:newKindBegin];
	m_Warrior.state = newKind;
}

-(BOOL)IsGuanAttackOver:(int)attackKind
{
	int offAction = 0;
	if(attackKind == Normal_Attack)
		offAction = GUAN_HIT_LEFT;
	else
	{
		offAction = GUAN_HUOQIANG_LEFT;
	}

	//当前动画索引
	int nowIndex = [self GetEnemyMoveActionIndex:m_Warrior.direction]+offAction;
	return [[__guanActionArray objectForKey:[NSNumber numberWithInt:nowIndex]] IsPlayOver];
}

-(void)AddApertureGuanYu
{
	__apertureSpr = [CCSprite node];
	NSMutableArray* animFrames = [NSMutableArray array];
	CCTexture2D*pTexture = [[CCTextureCache sharedTextureCache]addImage:@"texiao_guangquan.png"];
	for(int i=0;i<4;i++)
	{
		int width  = pTexture.contentSize.width;
		int height = pTexture.contentSize.height/4;
		CGRect imageRect = CGRectMake(0, height*i, width, height);
		CCSpriteFrame * addFrame= [CCSpriteFrame frameWithTexture:pTexture rect:imageRect offset:CGPointMake(0, 0)];
		[animFrames addObject:addFrame];
	}
	CCAnimation * pCCAnimation = [CCAnimation animationWithName:@"GUANYU_aperture" delay:0.1 frames:animFrames];
	[__apertureSpr runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:pCCAnimation restoreOriginalFrame:YES]]];
	
	[__apertureSpr setScale:0.6];
	[m_Map addChild:__apertureSpr z:LAYER_ITEM_APERTURE];
	__apertureSpr.position = m_Warrior.position;
}

-(int)GuanAnimationIndex
{
	return m_Warrior.state*4+GUAN_WAIT_LEFT;
}


#pragma mark 玩家操作点击地图
//点击可移动地点
-(void)TouchMovePoint:(CGPoint)tPoint IsEnableMove:(BOOL)isAble;
{
	int tagfile = DISABLE_POINT;
	
	if(isAble == YES)
	{
		tagfile = ENABLE_POINT;
	}
	//点击地点提示动画
	CActionSpriteW * pTwo = [[CAnimationStoreW ShareAnimationStore] CreateActionSprite:
							 0 doubleTime:AccelerateNum cyc:false fileTag:tagfile];
	[pTwo StartPlay];//显示动画
	pTwo.position = tPoint;
	//添加到最底层
	[m_Map addChild:pTwo z:1];
	[pTwo setScale:0.5];
}

#pragma mark 关羽攻击

-(void)GuanYuAttackOver
{
	
	int warrior_attck = m_Warrior.attack;
	if (m_Warrior.isAngery) //攻击结束敌兵掉血
	{
		warrior_attck= m_Warrior.attack * 2;
		m_Warrior.angeryTimeLeft--;
		if (m_Warrior.angeryTimeLeft <= 0) 
		{
			m_Warrior.isAngery = NO;
			m_Warrior.angeryTimeLeft = 0;
			__attackKind = Normal_Attack;
		}
	}
	m_Warrior.target.hp = m_Warrior.target.hp-warrior_attck;
	if(__b_touch)//如果在攻击时点击地图,攻击结束马上移动
	{
		__b_touch = false;
		[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_ATTACK newAction:WARRIOR_RUN];
		[self TouchMovePoint:__b_touchPoint IsEnableMove:YES];
		return;
	}
	if (m_Warrior.target.hp < 0 || 1 == m_Warrior.target.status)//小兵死亡,武将进入等待状态,搜寻目标 
	{
		[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_ATTACK newAction:WARRIOR_STAND];
		
		return;
	}
	

	//敌兵在攻击范围内
	if ([self IsImpactCircle:m_Warrior.position range1:m_Warrior.attackRadius center2:m_Warrior.target.position range2:m_Warrior.target.range]) 
	{
		[self ChangeGuanAttackDirect];
		[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_ATTACK newAction:WARRIOR_ATTACK];
		return;
	}
	
	//敌兵不在攻击范围内,追踪
	//目标未死亡,如果还在攻击范围内,继续攻击如果不在,追踪攻击.
	Location *targetLoc = [self GetLocation:m_Warrior.target.position];
	
	if (!(targetLoc.x == m_Warrior.end.x && targetLoc.y == m_Warrior.end.y))
	{
		m_Warrior.end = targetLoc;
		[m_MapManager MarkWarriorMap:m_Warrior.end];
		[m_MapManager WarriorCopyBack];
		[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_ATTACK newAction:WARRIOR_RUN];
	}
	[targetLoc release];
	
	[self WarriorRun];
}

-(void)ChangeGuanAttackDirect
{
	//方向 1右边   2上边   3下边     4左边
	CGPoint warPoint = m_Warrior.position;
	CGPoint ePoint = m_Warrior.target.position;
	int oldDirect = m_Warrior.direction;
	if(warPoint.x == ePoint.x)
	{
		if(warPoint.y > ePoint.y)
		{
			m_Warrior.direction = Down_Direction;
		}
		else
		{
			m_Warrior.direction = Up_Direction;
		}

	}
	else
	{
		if(warPoint.x < ePoint.x)
		{
			m_Warrior.direction = Right_Direction;
		}
		else 
		{
			m_Warrior.direction = Left_Direction;
		}

	}
	if(oldDirect != m_Warrior.direction)
	{
		[self ChangeWarrirDirection:oldDirect oldKind:[self GuanAnimationIndex] actionKind:[self GuanAnimationIndex]];
	}

}

#pragma mark 关羽移动
//关羽移动后判断下一步移动方位和位置
-(BOOL)CheckGuanYuNextMove:(float)delta
{
	//下一个移动点的坐标
	m_Warrior.position = [self GetPos:m_Warrior.nextLocation];
	//当前坐标
	m_Warrior.location = m_Warrior.nextLocation;
	Location *temploc = nil;
	//当前地图坐标
	@try {
		temploc = [m_MapManager GetWarriorNextLocation:m_Warrior.location];
	}
	@catch (NSException * e) 
	{
		[temploc release];
		[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_RUN newAction:WARRIOR_STAND];
		return false;
	}
	@finally 
	{
		if (temploc) 
		{
			m_Warrior.nextLocation = temploc;
			m_Warrior.direction = [self GetDirectionFromLocation:m_Warrior.location toLocation:m_Warrior.nextLocation];
			switch (m_Warrior.direction) 
			{
				case 1:
				{
					m_Warrior.position.x += delta;
				}
					break;
				case 2:
				{
					m_Warrior.position.y += delta;
				}
					break;
				case 3:
				{
					m_Warrior.position.y -= delta;
				}
					break;
				case 4:
				{
					m_Warrior.position.x -= delta;
				}
					break;
				default:
					break;
			}
		}
		else 
		{
			
		}
		[temploc release];
	}

	return true;
}

#pragma mark 关羽技能动画
//回调技能释放完毕
-(void)CallSkillFireOver:(float)fireTime SkillName:(int)skillKind
{
	//fireTime = 10;
	if(__skillFireArray == nil)
	{
		__skillFireArray = [[NSMutableArray alloc] init];
	}
	[__skillFireArray addObject:[NSNumber numberWithInt:skillKind]];
	[self schedule:@selector(StopSkill) interval:fireTime];
	
}
//显示八卦阵
-(void)PlaySkill:(CGPoint)usePoint
{
	float skill_time =0;
	int fileOne = GUANYUBAGUAONE;
	int fileTwo = GUANYUBAGUATWO;
	int zmap1 = 0;
	int zmap2 = 0;
	switch (m_SkillSelect) //选择对应动画
	{
		case SKILL_LUOLEI:
		{
			fileOne = GUANYULEIJIONE;
			fileTwo = GUANYULEIJITWO;
			skill_time = [[Parameter sharedParameter] touQuLastTime];
			zmap1 = LAYER_ITEM_FASHU;
			zmap2 = LAYER_ITEM_FASHU;
			break;
		}
		case SKILL_TOUQU:
		{
			fileOne = GUANYUTOUQUONE;
			fileTwo = GUANYUTOUQUTWO;
			skill_time = [[Parameter sharedParameter] touQuLastTime];
			zmap1 = LAYER_ITEM_BAGUA;
			zmap2 = LAYER_ITEM_FASHU;
			break;
		}
		default:
		{
			fileOne = GUANYUBAGUAONE;
			fileTwo = GUANYUBAGUATWO;
			skill_time = [[Parameter sharedParameter] luoLeiAttackTime:m_Warrior.level];
			zmap1 = LAYER_ITEM_BAGUA;
			zmap2 = LAYER_ITEM_FASHU;
			break;
		}
	}
	BOOL bOneCyc = YES;
	if(m_SkillSelect == SKILL_LUOLEI)
		bOneCyc = NO;
	
	skill_time = skill_time*1.0/60.0;
	CActionSpriteW * pOne = [[CAnimationStoreW ShareAnimationStore] CreateActionSprite:
							0 doubleTime:AccelerateNum cyc:bOneCyc fileTag:fileOne];
	
	[pOne StartPlay];
	[m_Map addChild:pOne z:zmap1 ];
	pOne.position = CGPointMake(usePoint.x, usePoint.y);
	[pOne setScale:0.7];

	BOOL bCyc = NO;
	if(m_SkillSelect == SKILL_TOUQU)
		bCyc = YES;
	
	
	CActionSpriteW * pTwo = [[CAnimationStoreW ShareAnimationStore] CreateActionSprite:
							 0 doubleTime:AccelerateNum cyc:bCyc fileTag:fileTwo];
	
	[pTwo StartPlay];
	[m_Map addChild:pTwo z:zmap2];
	pTwo.position = CGPointMake(usePoint.x, usePoint.y);

	[self CallSkillFireOver:skill_time SkillName:m_SkillSelect];
	switch (m_SkillSelect) 
	{
		case SKILL_BAGUA:
		{
			[__BaGuaOneAction addObject:pOne];
			[__BaGuaTwoAction addObject:pTwo];
			break;
		}
		case SKILL_LUOLEI:
		{
			[__LuoLeiOneAction addObject:pOne];
			[__LuoLeiTwoAction addObject:pTwo];
			break;
		}
		case SKILL_TOUQU:
		{
			[__TouquOneAction addObject:pOne];
			[__TouquTwoAction addObject:pTwo];
			break;
		}
		default:
		{
			[MyExcetion ThorwException:@"PlaySkill" resultStr:@"Skill play error!"];
			break;
		}
	}
}

-(void)StopSkill
{
	if([__skillFireArray count] == 0)
		return;
	int skillKind = [[__skillFireArray objectAtIndex:0]intValue];
	[__skillFireArray removeObjectAtIndex:0];
	NSMutableArray * pArray = nil;
	NSMutableArray * ptwoArray = nil;
	switch (skillKind) 
	{
		case SKILL_BAGUA:
		{
			pArray = __BaGuaOneAction;
			break;
		}
		case SKILL_LUOLEI:
		{
			pArray = __LuoLeiOneAction;
			ptwoArray = __LuoLeiTwoAction;
			break;
		}
		case SKILL_TOUQU:
		{
			pArray = __TouquOneAction;
			ptwoArray = __TouquTwoAction;
			break;
		}
		default:
		{
			[MyExcetion ThorwException:@"StopSkill" resultStr:@"Skill Stop error!"];
			break;
		}
	}
	
	for(unsigned int i =0; i<[pArray count];i++)
	{
		if([[pArray objectAtIndex:i] visible] == YES)
		{
			[[pArray objectAtIndex:i] setVisible:NO];
			if(ptwoArray != nil)
				[[ptwoArray objectAtIndex:i] setVisible:NO];
			return;
		}
	}
}

//判断当前是否有闲置的武将技能
-(BOOL)IsWarriorSkillFree:(NSMutableArray*)skillArray TwoAction:(NSMutableArray*)skillTwoArray playPoint:(CGPoint)usePoint
{
	if([[skillArray objectAtIndex:0] visible] == NO)
	{
		//[[skillArray objectAtIndex:0] setVisible:YES];
		[[skillArray objectAtIndex:0] StartPlay];
		[[skillTwoArray objectAtIndex:0] StartPlay];
		[[skillArray objectAtIndex:0] setPosition:usePoint];
		[[skillTwoArray objectAtIndex:0]setPosition:usePoint];
		return true;
	}
	else
	{
		return false;
	}

}

-(void)PlayWarriorSkill:(CGPoint)usePoint;
{
	float skill_time = 0;
	if(__skillFireArray == nil)
		__skillFireArray = [NSMutableArray array];
	switch (m_SkillSelect) //判断如果有可用的冷却动画技能,发达,如果没有创建新的动画,添加到地图中.
	{
		case SKILL_BAGUA:
		{
			if([self IsWarriorSkillFree:__BaGuaOneAction TwoAction:__BaGuaTwoAction playPoint:usePoint])
			{
				skill_time = [[Parameter sharedParameter] baGuaLastTime]*1.0/60.0;
				[self CallSkillFireOver:skill_time SkillName:SKILL_BAGUA];
				return;
			}
			break;
		}
		case SKILL_LUOLEI:
		{
			if([self IsWarriorSkillFree:__LuoLeiOneAction TwoAction:__LuoLeiTwoAction playPoint:usePoint])
			{
				skill_time = [[Parameter sharedParameter] luoLeiAttackTime:m_Warrior.level]*1.0/60.0;
				[self CallSkillFireOver:skill_time SkillName:SKILL_LUOLEI];
				return;
			}
			break;
		}
		case SKILL_TOUQU:
		{
			if([self IsWarriorSkillFree:__TouquOneAction TwoAction:__TouquTwoAction playPoint:usePoint])
			{
				skill_time = [[Parameter sharedParameter] touQuLastTime]*1.0/60.0;
				[self CallSkillFireOver:skill_time SkillName:SKILL_TOUQU];
				return;
			}
			break;
		}
		default:
		{
			[MyExcetion ThorwException:@"PlayWarriorSkill" resultStr:@"Skill play error!"];
		}
			break;
	}
	//添加新的技能动画
	[self PlaySkill:usePoint];
}

-(void)SkillIconMove:(BOOL)b_back
{
	int X = 50;
	int Y = 0;
	if(b_back == YES)
		X=-50;
	
	id actionOne = [CCMoveBy actionWithDuration:0.2 position:ccp(X,Y)];
	id actionTwo = [CCMoveBy actionWithDuration:0.2 position:ccp(X,Y)];
	id actionThree = [CCMoveBy actionWithDuration:0.2 position:ccp(X,Y)];
	id actionFour = [CCMoveBy actionWithDuration:0.2 position:ccp(X,Y)];
	
	[m_IconSkill_1 runAction:[CCSequence actions:actionOne,nil]];
	[m_IconSkill_2 runAction:[CCSequence actions:actionTwo,nil]];
	[m_IconSkill_3 runAction:[CCSequence actions:actionThree,nil]];
	[m_IconSkill_4 runAction:[CCSequence actions:actionFour,nil]];
	
}

-(void)AddSkillAreaMap:(BOOL)IsEnable
{
	int Icon_width = 156/2;
	int Icon_height = 234/3;
	int g_width= 120;
	int g_height = 240;
	if(__fireSkill != nil)
	{
		//[__fireSkill release];
	}
	__fireSkill = [CCSprite node];
	CGRect gRect;
	int x_begin = 0;
	if(IsEnable)
	{
		gRect = CGRectMake(0, 0, g_width, g_height);
		
	}
	else
	{
		x_begin = Icon_width;
		gRect = CGRectMake(g_width, 0, g_width, g_height);
	}
	//左半圆
	CCSprite * l_g = [CCSprite spriteWithFile:@"shifa.png"rect:gRect];
	//右半圆
	CCSprite * r_g = [CCSprite spriteWithFile:@"shifa.png"rect:gRect];
	l_g.position = CGPointMake(-60, 0);
	r_g.position = CGPointMake(60, 0);
	[__fireSkill addChild:l_g z:1];
	[__fireSkill addChild:r_g z:1];
	[r_g setRotation:180];
	
	gRect = CGRectMake(x_begin, Icon_height*(2-m_SkillSelect), Icon_width, Icon_height);
	CCSprite * iconSpr = [CCSprite spriteWithFile:@"shifa2.png" rect:gRect];
	[__fireSkill addChild:iconSpr z:2];
	
	[m_Map addChild:__fireSkill z:22];
	
	__fireSkill.position = ccp(1000,1000);
	
	[__fireSkill setScale:0.6];
	
}

-(void)LuoLeiEffect:(EffectLuoLei * )pluolei
{
	for(Enemy* enemy in m_EnemyList)
	{
		if([self IsImpactCircle:enemy.position range1:enemy.range center2:pluolei.position range2:pluolei.range])
		{
			enemy.hp = enemy.hp-pluolei.attack;
			if(enemy.hp <=0)
				enemy.hp = 0;
		}
	}
}

-(BOOL)IsGuanDoSkillOver
{
	int offAction =0;
	if(m_SkillSelect != SKILL_HUOQIANG)
	{
		offAction = GUAN_SHIFA_LEFT;
	}
	else
	{
		offAction = GUAN_HUOQIANG_LEFT;
	}
	//当前动画索引
	int nowIndex = [self GetEnemyMoveActionIndex:m_Warrior.direction]+offAction;
	return [[__guanActionArray objectForKey:[NSNumber numberWithInt:nowIndex]] IsPlayOver];
}

-(void)WarriorSkillEffect
{
	if([__touchSkillArray count]<=0)
	{
		return;
	}
	
	int m_SkillUse = [[__touchSkillArray objectAtIndex:0] intValue];
	Location *loc = [__touchLocArray objectAtIndex:0];
	CGPoint usePoint = [self GetPos:loc];

	if(m_SkillUse != SKILL_HUOQIANG)//
	{
		[self PutEffect:m_SkillUse usePoint:usePoint];
	}
	else
	{
		m_Warrior.isAngery = YES;
		m_Warrior.angeryTimeLeft = [[Parameter sharedParameter] BaoJiTime];
		__attackKind = Fire_Attack;
	}

	[self GuanRunStop:m_Warrior.direction oldAction:WARRIOR_STAND newAction:WARRIOR_SHIFA];
	
	[__touchSkillArray removeObjectAtIndex:0];
	[__touchLocArray removeObjectAtIndex:0];

}

-(void)TouchSKillIcon:(Location*)loc
{
	[__touchLocArray addObject:loc];
	[__touchSkillArray addObject: [NSNumber numberWithInt: m_SkillSelect]];
}

-(void)HuoqiangFire
{
	CActionSpriteW * Fire = [[CAnimationStoreW ShareAnimationStore] CreateActionSprite:
							 0 doubleTime:AccelerateNum*2.0 cyc:false fileTag:GUANYUPENHUO];
	
	[Fire StartPlay];
	
	Fire.position = m_Warrior.target.position;
	switch (m_Warrior.direction)
	{
		case Right_Direction:
		{
			
			break;
		}
		case Up_Direction:
		{
			break;
		}
		case Down_Direction:
		{
			break;
		}
		case Left_Direction:
		{
			break;
		}
		default:
			break;
	}
	[m_Map addChild:Fire z:LAYER_ITEM_SKILL];
}

-(BOOL)IsSkillEnable
{
	return true;
}

@end
